添加边权重以在 networkx 中绘制输出 [英] Add edge-weights to plot output in networkx
本文介绍了添加边权重以在 networkx 中绘制输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 networkx 包在 python 中做一些图论.我想将图形边缘的权重添加到绘图输出中.我怎样才能做到这一点?
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?
例如,我将如何修改以下代码以获得所需的输出?
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")
我希望 0.5 和 9.8 出现在它们在图中所指的边上.
I would like 0.5 and 9.8 to appear on the edges to which they refer in the graph.
推荐答案
您必须致电 nx.draw_networkx_edge_labels()
,这将允许您...绘制 networkX 边缘标签 :)
You'll have to call nx.draw_networkx_edge_labels()
, which will allow you to... draw networkX edge labels :)
完全修改的源
#!/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>)
这篇关于添加边权重以在 networkx 中绘制输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文