添加边缘权重以绘制networkx中的输出 [英] Add edge-weights to plot output in networkx

查看:2917
本文介绍了添加边缘权重以绘制networkx中的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在python中使用networkx软件包做一些图论。我希望
将图形边缘的权重添加到绘图输出中。我怎样才能做到这一点?



例如,我会如何修改以下代码以获得所需的输出?

  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 
导入networkx为nx
导入matplotlib.pyplot为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>)


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")

I would like 0.5 and 9.8 to appear on the edges to which they refer in the graph.

解决方案

You'll have to call nx.draw_networkx_edge_labels(), which will allow you to... draw networkX edge labels :)

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>)

这篇关于添加边缘权重以绘制networkx中的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆