我正在使用 networkx 包在 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)
plt.savefig("path.png")
我希望 0.5 和 9.8 出现在图表中它们所指的边上。
最佳答案
您必须调用 nx.draw_networkx_edge_labels()
,这将允许您...绘制networkX边缘标签:)
编辑:完全修改的源代码
#!/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>)
关于python - 添加边缘权重以在 networkx 中绘制输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28372127/