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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20381460/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:18:16  来源:igfitidea点击:

Networkx: how to show node and edge attributes in a graph drawing

pythongraphviznetworkx

提问by Bravo

I have a graph G with attribute 'state' for nodes and edges. I want to draw the graph, all nodes labelled, and with the state marked outside the corresponding edge/node.

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

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'

The command draw.networkx has an option for labels, but I do not understand how to provide the attribute as a label to this command. Could someone help me out?

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

回答by Aric

It's not so pretty - but it works like this:

它不是那么漂亮 - 但它的工作原理是这样的:

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

在此处输入图片说明