Python 添加边权重以在 networkx 中绘制输出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28372127/
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
Add edge-weights to plot output in networkx
提问by smilingbuddha
I am doing some graph theory in python using the networkx package. I would like to add the weights of the edges of my graph to the plot output. How can I do this?
我正在使用 networkx 包在 python 中做一些图论。我想将图形边缘的权重添加到绘图输出中。我怎样才能做到这一点?
For example How would I modify the following code to get the desired output?
例如,我将如何修改以下代码以获得所需的输出?
import networkx as nx
import matplotlib.pyplot as plt
G=nx.Graph()
i=1
G.add_node(i,pos=(i,i))
G.add_node(2,pos=(2,2))
G.add_node(3,pos=(1,0))
G.add_edge(1,2,weight=0.5)
G.add_edge(1,3,weight=9.8)
pos=nx.get_node_attributes(G,'pos')
nx.draw(G,pos)
plt.savefig("path.png")
I would like 0.5 and 9.8 to appear on the edges to which they refer in the graph.
我希望 0.5 和 9.8 出现在它们在图中所指的边上。
采纳答案by Marcus Müller
You'll have to call nx.draw_networkx_edge_labels()
, which will allow you to... draw networkX edge labels :)
您必须调用nx.draw_networkx_edge_labels()
,这将允许您...绘制 networkX 边缘标签 :)
EDIT: full modified source
编辑:完全修改源
#!/usr/bin/python
import networkx as nx
import matplotlib.pyplot as plt
G=nx.Graph()
i=1
G.add_node(i,pos=(i,i))
G.add_node(2,pos=(2,2))
G.add_node(3,pos=(1,0))
G.add_edge(1,2,weight=0.5)
G.add_edge(1,3,weight=9.8)
pos=nx.get_node_attributes(G,'pos')
nx.draw(G,pos)
labels = nx.get_edge_attributes(G,'weight')
nx.draw_networkx_edge_labels(G,pos,edge_labels=labels)
plt.savefig(<wherever>)
回答by Julio
I like to do it like this:
我喜欢这样做:
import matplotlib.pyplot as plt
pos=nx.planar_layout(G) # pos = nx.nx_agraph.graphviz_layout(G)
nx.draw_networkx(G,pos)
labels = nx.get_edge_attributes(G,'weight')
nx.draw_networkx_edge_labels(G,pos,edge_labels=labels)