用NetworkX有一段时间了,本文从构建一张图要素出发,整理NetworkX基本操作,包括声明图类型、添加边、添加顶点。
1. 概述
NetworkX is a Python language software package for the creation, manipulation, and study of the structure, dynamics, and functions of complex networks.
NetworkX最吸引我的两个地方是:
Nodes can be arbitrary (hashable) Python objects except None (e.g. text, images, XML records)
Edges can hold arbitrary data (e.g. weights, time-series)
再加上Python强大的字典功能,这意味着可以用NetworkX构建一张内容丰富的图。官方网站和使用文档如下:
2. 构建一张图
2.1 定义图的类型
NetworkX按边是否有向和是否允许重边将图分成4种:Graph、DiGraph、MultiGraph、MultiDiGraph。这4种图皆请允许自环。根据实际需要,用下面语句之一创建一张图:
# 使用举例
G = nx.Graph() # Undirected graphs with self loops
G = nx.DiGraph() # DiGraphDirected graphs with self loops
G = nx.MultiGraph() # Directed graphs with self loops and parallel edges
G = nx.MultiDiGraph() # Undirected graphs with self loops and parallel edges
# Graph types
Graph(data=None, **attr) # Undirected graphs with self loops
DiGraph(data=None, **attr) # Directed graphs with self loops
MultiGraph(data=None, **attr) # Undirected graphs with self loops and parallel edges
MultiDiGraph(data=None, **attr) # Directed graphs with self loops and parallel edges
data和属性attr默认都是空,详细描述如下:
data: can be an edge list, any NetworkX graph object; a NumPy matrix, 2d ndarray, a SciPy sparsekey/value attributes matrix, a PyGraphviz graph
attr: key/val