[英]Add edge-weights to plot output in networkx
我正在使用 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>)
我喜歡這樣做:
import matplotlib.pyplot as plt
pos=nx.spring_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)
如何在 python 中制作一個程序,它將生成以下內容:
nadeem awan 電子郵件地址:silky.awan@gmail.com
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.