Python之Networkx详解


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())


  • 22
    点赞
  • 189
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值