[英]Problems printing weight in a NetworkX graph
我正在使用networkX閱讀邊緣列表。 邊緣列表包含以下形式的條目:
1; 2; 3
2; 3; 5
3; 1; 4
其中第三列是重量。 當我繪制此圖形時,它將權重3顯示為:
{'weight': 3}
而不只是3。最終,我希望能夠使用權重執行操作(例如,計算出的最高權重,僅顯示具有權重的邊:
'x'等
這是最小的工作代碼:
import networkx as nx
import pylab as plt
G=nx.Graph()
G=nx.read_edgelist('sample_with_weights.edges', data= (('weight',int),))
pos = nx.spring_layout(G)
nx.draw_networkx(G, pos=pos)
nx.draw_networkx_edge_labels(G, pos=pos)
nx.draw_networkx_edges(G,pos,width=4, edge_color='g', edge_labels = 'weight', arrows=False)
plt.show()
關於現有代碼的一些觀察:
該read_edgelist
不能與該邊緣列表文件一起很好地工作,因為“特殊”定界符;
尚未指定。
邊緣標簽應在draw_networkx_edge_labels
函數調用中指定,而不是在draw_networkx_edges
; 並且
edge_labels
是一個字典,由文本標簽的邊緣二元組(默認為“無”)作為鍵。 僅繪制字典中鍵的標簽。 (來自文檔 )
因此,一般的想法是使用edge_labels
有選擇地打印邊緣權重。 請在下面查看內聯注釋:
import networkx as nx
import pylab as plt
G=nx.Graph()
#Please note the use of the delimiter parameter below
G=nx.read_edgelist('test.edges', data= (('weight',int),), delimiter=";")
pos = nx.spring_layout(G)
#Here we go, essentially, build a dictionary where the key is tuple
#denoting an edge between two nodes and the value of it is the label for
#that edge. While constructing the dictionary, do some simple processing
#as well. In this case, just print the labels that have a weight less
#than or equal to 3. Variations to the way new_labels is constructed
#produce different results.
new_labels = dict(map(lambda x:((x[0],x[1]), str(x[2]['weight'] if x[2]['weight']<=3 else "") ), G.edges(data = True)))
nx.draw_networkx(G, pos=pos)
#Please note use of edge_labels below.
nx.draw_networkx_edge_labels(G, pos=pos, edge_labels = new_labels)
nx.draw_networkx_edges(G,pos,width=4, edge_color='g', arrows=False)
plt.show()
給定一個數據文件test.edges
看起來像...
1;2;3
2;3;3
3;4;3
2;4;4
4;6;5
1;6;5
...上面的代碼片段將產生類似於以下內容的結果:
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.