Python之Networkx详解

文章目录

        • 1. 安装Networkx
        • 2. Networkx的基本使用
          • 2.1 导入networkx
          • 2.2 创建Graph
          • 2.3 给Graph添加边
          • 2.3 Graph基本信息获取
          • 2.4 Graph的绘制
          • 2.5 Graph的其他内置算法
        • 3 其他
          • 3.1 read_edgelist( )

Networkx是一个Python的包,可以用来创建和处理复杂的图网络结构。

中文教程: https://www.osgeo.cn/networkx/install.html
英文教程: https://networkx.org/documentation/stable/install.html

1. 安装Networkx

# 使用pip安装
pip install networkx

# 使用conda安装
conda install networkx

2. Networkx的基本使用

2.1 导入networkx
import networkx as nx
2.2 创建Graph
G = nx.Graph()          # 无向图
G = nx.DiGraph()        # 有向图
G = nx.MultiGraph()     # 多重无向图
G = nx.MultiDigraph()   # 多重有向图
G.clear()               # 清空图

根据定义,Graph 是一组节点(顶点)和已识别的节点对(称为边、链接等)的集合。在NetworkX中,节点可以是任何 hashable 对象,例如文本字符串、图像、XML对象、另一个图形、自定义节点对象等。

2.3 给Graph添加边
G.add_edge(1, 2)             # default edge data=1
G.add_edge(2, 3, weight=0.9) # specify edge data
# 如果是边有许多的权,比如有长度和宽度的属性,那么:
G.add_edge(n1, n2, length=2, width=3)
 
elist = [(1, 2), (2, 3), (1, 4), (4, 2)]
G.add_edges_from(elist)
elist = [('a', 'b', 5.0), ('b', 'c', 3.0), ('a', 'c', 1.0), ('c', 'd', 7.3)]
G.add_weighted_edges_from(elist)
 
# 如果给结点的名称是其它符号,想离散化成从x开始的数字标记,那么:
G = nx.convert_node_labels_to_integers(G, first_label=x)
2.3 Graph基本信息获取
nx.info(G) # 图信息的概览
G.number_of_nodes()
G.number_of_edges()
# 获取和节点idx连接的边的attr属性之和
G.in_degree(idx, weight='attr')
 
# 如果想知道某个结点相连的某个边权之和:
DG.degree(nodeIdx, weight='weightName')
 
# 获取结点或者边的属性集合,返回的是元组的列表
G.nodes.data('attrName')
G.edges.data('attrName')
 
# 获取n1 n2的边的length权重,那么:
G[n1][n2]['length']
# 如果是有重边的图,选择n1,n2第一条边的length权重,则:
G[n1][n2][0]['length']
 
# 获取n1结点的所有邻居
nx.all_neighbors(G, n1)
 
# 判断图中n1到n2是否存在路径
nx.has_path(G, n1, n2)
# 根据一个结点的list,获取子图
subG = nx.subgraph(G, nodeList)
2.4 Graph的绘制
# 最简单的绘制
import matplotlib.pyplot as plt
nx.draw(G)
plt.show()
 
# 设置其他相关参数
nx.draw(G,
    with_labels=True,
    pos = nx.sprint_layout(G),
    node_color=color_list,
    edge_color='k',
    node_size=100,
    node_shape='o',
    linewidths=2,
    width=1.0,
    alpha=0.55,
    style='solid',
    font_size=9,
    font_color='k'
)
2.5 Graph的其他内置算法
# 最短路算法 返回最短路的路径列表
nx.shortest_path(G, n1, n2, method='dijkstra')

# 以及各种图的算法,比如流,割等等等等,大家可以看文档探索下

3 其他

3.1 read_edgelist( )

Read a graph from a list of edges.
函数定义如下:

 read_edgelist(path, comments='#', delimiter=None, create_using=None, nodetype=None, data=True, edgetype=None, encoding='utf-8'):
    '''
    Read a graph from a list of edges.
    
    Parameters :	
    path : file or string
        File or filename to write. If a file is provided, it must be opened in ‘rb’ mode. Filenames ending in .gz or .bz2 will be uncompressed.

    comments : string, optional
        The character used to indicate the start of a comment.
        
    delimiter : string, optional
        The string used to separate values. The default is whitespace.
        
    create_using : Graph container, optional,
        Use specified container to build graph. The default is networkx.Graph, an undirected graph.

    nodetype : int, float, str, Python type, optional
        Convert node data from strings to specified type

    data : bool or list of (label,type) tuples
        Tuples specifying dictionary key names and types for edge data

    edgetype : int, float, str, Python type, optional OBSOLETE
        Convert edge data from strings to specified type and use as ‘weight’

    encoding: string, optional
        Specify which encoding to use when reading file.

    Returns :	
    G : graph
        A networkx Graph or other type specified with create_using
    '''

样例:

nx.write_edgelist(nx.path_graph(4), "test.edgelist")
G=nx.read_edgelist("test.edgelist")

fh=open("test.edgelist", 'rb')
G=nx.read_edgelist(fh)
fh.close()

G=nx.read_edgelist("test.edgelist", nodetype=int) G=nx.read_edgelist("test.edgelist",create_using=nx.DiGraph())


你可能感兴趣的:(Python)