NetworkX系列教程(4)-设置graph的信息

要画出美观的graph,需要对graph里面的节点,,节点的布局都要进行设置,具体可以看官方文档:Adding attributes to graphs, nodes, and edges部分.

注意:如果代码出现找不库,请返回第一个教程,把库文件导入.

设置graph的信息

创建graph时添加属性

1
2
3
4
5
6
#G.clear()
G=nx.Graph()
G = nx.Graph(day="Friday")
print('Assign graph attributes when creating a new graph: ',G.graph)
G.graph['day'] = "Monday"
print('Assign graph attributes when have a graph: ',G.graph)

输出:

Assign graph attributes when creating a new graph: {‘day’: ‘Friday’}
Assign graph attributes when have a graph: {‘day’: ‘Monday’}

指定节点的属性

1
2
3
4
5
6
7
8
9
#创建时设置
G.add_node(1, time='5pm')
G.add_nodes_from([3,4], time='2pm',color='g')

#直接设置
G.nodes[1]['room'] = 714
G.nodes[1]['color'] = 'b'

print(G.nodes.data())

输出:

[(1, {‘room’: 714, ‘time’: ‘5pm’, ‘color’: ‘b’}), (3, {‘time’: ‘2pm’, ‘color’: ‘g’}), (4, {‘time’: ‘2pm’, ‘color’: ‘g’})]

指定边的属性

1
2
3
4
5
6
7
8
9
10
11
12
13
#创建时设置
G.add_edge(1, 2, weight=4.7 )
G.add_edges_from([(3, 4), (4, 5)], color='red',weight=10)
G.add_edges_from([(1, 2, {'color': 'blue'}), (2, 3, {'weight': 8})])

#直接设置
G[1][2]['weight'] = 4.7
G[1][2]['color'] = "blue"
G.edges[3, 4]['weight'] = 4.2
G.edges[1, 2]['color'] = "green"

print('edge 1-2: ',G.edges[1,2])
print('edge 3-4: ',G.edges[3,4])

输出:

edge 1-2: {‘weight’: 4.7, ‘color’: ‘green’}
edge 3-4: {‘weight’: 4.2, ‘color’: ‘red’}

显示graph

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#生成节点标签
labels={}
labels[1]='1'
labels[2]='2'
labels[3]='3'
labels[4]='4'
labels[5]='5'

#获取graph中的边权重
edge_labels = nx.get_edge_attributes(G,'weight')
print('weight of all edges:',edge_labels)

#生成节点位置
pos=nx.circular_layout(G)
print('position of all nodes:',pos)

#把节点画出来
nx.draw_networkx_nodes(G,pos,node_color='g',node_size=500,alpha=0.8)

#把边画出来
nx.draw_networkx_edges(G,pos,width=1.0,alpha=0.5,edge_color='b')

#把节点的标签画出来
nx.draw_networkx_labels(G,pos,labels,font_size=16)

#把边权重画出来
nx.draw_networkx_edge_labels(G, pos, edge_labels)

plt.axis('on')
#去掉坐标刻度
plt.xticks([])
plt.yticks([])
plt.show()

输出:

weight of all edges: {(1, 2): 4.7, (3, 4): 4.2, (2, 3): 8, (4, 5): 10}
position of all nodes: {1: array([1.00000000e+00, 2.38418583e-08]), 2: array([0.30901696, 0.95105658]), 3: array([-0.80901709, 0.58778522]), 4: array([-0.80901698, -0.58778535]), 5: array([ 0.30901711, -0.95105647])}

有权无向图