添加边权重以打印networkx中的输出

2024-05-12 18:34:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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出现在图中它们所指的边上。


Tags: posimportnetworkxaddnode绘图as图表
1条回答
网友
1楼 · 发布于 2024-05-12 18:34:47

你必须打电话给^{},这样你就可以。。。绘制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>)

相关问题 更多 >