Networkx:如何在图形绘制中显示节点和边缘属性

时间:2013-12-04 17:02:10

标签: python graphviz networkx

我有一个图G,节点和边的属性'state'。我想绘制图形,标记所有节点,并在相应的边/节点外标记状态。

for v in G.nodes():     
    G.node[v]['state']='X'
G.node[1]['state']='Y' 
G.node[2]['state']='Y'

for n in G.edges_iter():    
    G.edge[n[0]][n[1]]['state']='X'
G.edge[2][3]['state']='Y'

命令draw.networkx有一个标签选项,但我不明白如何将该属性作为标签提供给此命令。有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:25)

它不是那么漂亮 - 但它的工作原理如下:

from matplotlib import pyplot as plt
import networkx as nx
G = nx.Graph()
G.add_edge(1,2)
G.add_edge(2,3)
for v in G.nodes():
    G.node[v]['state']='X'
G.node[1]['state']='Y'
G.node[2]['state']='Y'

for n in G.edges_iter():
    G.edge[n[0]][n[1]]['state']='X'
G.edge[2][3]['state']='Y'

pos = nx.spring_layout(G)

nx.draw(G, pos)
node_labels = nx.get_node_attributes(G,'state')
nx.draw_networkx_labels(G, pos, labels = node_labels)
edge_labels = nx.get_edge_attributes(G,'state')
nx.draw_networkx_edge_labels(G, pos, labels = edge_labels)
plt.savefig('this.png')
plt.show()

enter image description here