究竟是什么对象可以作为 NetworkX 中的节点与边,NetworkX 并没有做限定。节点与边可以是您定义的任何可支持的有意义的对象。普遍的选择是数字、字符串,除了节点可以是任何可哈希的 Python 对象(None 除外),而边可以使用 G.add_edge(n1, n2, object=x) 创建联系的任何对象 x。
As an example, n1 and n2 could be protein objects from the RCSB Protein Data Bank, and x could refer to an XML record of publications detailing experimental observations of their interaction.
We have found this power quite useful, but its abuse can lead to unexpected surprises unless one is familiar with Python. If in doubt, consider using convert_node_labels_to_integers() to obtain a more traditional graph with integer labels.
为边添加属性
import networkx as nx
from matplotlib import pyplot as plt
%matplotlib inline
G = nx.Graph() # 创建空图
G.add_edge(1, 2, length = 10) # 为边 (1,2) 添加属性 length = 10
G.add_edge(1, 3, weight = 20) # 为边 (1,3) 添加属性 weight = 20
G.add_edge(2, 3, capacity = 15) # 为边 (2,2) 添加属性 capacity = 15
nx.draw(G) # 画出图
图1 带属性的边组成的图
图2 查看邻域与边的属性
可以为边添加新的属性:
G[1][3]['color'] = 'red' # 等价于 G[1][3].update({'color': 'red'})
更多方法见:
>>> G.add_edge(1, 2, weight=4.7 )
>>> G.add_edges_from([(3, 4), (4, 5)], color='red')
>>> G.add_edges_from([(1, 2, {'color': 'blue'}), (2, 3, {'weight': 8})])
>>> G[1][2]['weight'] = 4.7
>>> G.edges[3, 4]['weight'] = 4.2
为图添加属性
G = nx.Graph(day='Friday')
G.graph
显示为:{'day': 'Friday'}。
当然也可以继续添加或者修改属性:
G = nx.Graph()
G.graph['day'] = 'Friday'
G.graph
为节点添加属性
同样也可以为节点添加属性:
>>> G.add_node(1, time='5pm')
>>> G.add_nodes_from([3], time='2pm')
>>> G.nodes[1]
{'time': '5pm'}
>>> G.nodes[1]['room'] = 714
>>> G.nodes.data()
NodeDataView({1: {'time': '5pm', 'room': 714}, 3: {'time': '2pm'}})