[英]How to show number of connections as edge label and weight based on number of connections
如何根據連接數將連接數顯示為邊緣標簽和邊緣權重。
到目前為止,我的代碼:
import networkx as nx
import matplotlib.pyplot as plt
G=nx.DiGraph()
G.add_edge('a','b');
G.add_edge('c','d');
G.add_edge('c','a');
G.add_edge('a','b');
G.add_edge('b','a');
nx.draw(G,with_labels=True)
plt.show()
我的目標是基於大量數據創建圖(Python腳本)
網絡和matplotlib的新手
您遇到的基本問題是networkx
並不真正適合於繪制加權的有向圖。 可以做到的,但是不是很漂亮。 特別是,沒有真正的支持繪制雙向連接,因為雙向連接是相互繪制的。 下面,我嘗試通過在連接的頭部附近繪制邊緣權重來解決該問題,但這並不是很好。
import matplotlib.pyplot as plt
import networkx as nx
G=nx.MultiDiGraph()
G.add_edge('a','b');
G.add_edge('c','d');
G.add_edge('c','a');
G.add_edge('a','b');
G.add_edge('b','a');
edge_to_count = dict()
for edge in G.edges():
try:
edge_to_count[edge] += 1
except KeyError:
edge_to_count[edge] = 1
pos = nx.spring_layout(G)
nx.draw(G, pos)
nx.draw_networkx_edge_labels(G, pos, edge_to_count, label_pos=0.25)
plt.show()
如果要將多邊緣表示為邊緣權重,則代碼將更改為:
import matplotlib.pyplot as plt
import networkx as nx
# get edge weights based on edge count
edges = [('a','b'),
('c','d'),
('c','a'),
('a','b'),
('b','a')]
edge_to_count = dict()
for edge in edges:
try:
edge_to_count[edge] += 1.
except KeyError:
edge_to_count[edge] = 1.
# convert to networkx edge list format
edges = [(k[0], k[1], dict(weight=v)) for k, v in edge_to_count.items()]
# create graph
G = nx.DiGraph()
G.add_edges_from(edges)
# precompute layout to be used by both, draw() and draw_networkx_edge_labels
pos = nx.spring_layout(G)
# draw graph first, then labels on top
nx.draw(G, pos)
nx.draw_networkx_edge_labels(G, pos, edge_to_count, label_pos=0.25)
plt.show()
在某個時候,我花了一段時間解決這個確切的問題,所以我寫了一個自己的小網絡繪圖庫,稱為netgraph
(可通過pip和github獲得 )。 該API與networkx非常相似,除了我擺脫了一些我可能會為了向后兼容而保留在networkx中的命名不一致之處。 默認輸出如下所示:
如您所見,它支持繪制雙向/平行邊。 默認情況下,邊緣根據其重量着色。 由於它接受networkx圖形對象作為輸入,因此與networkx集成非常容易(它也支持多種輸入格式)。
import matplotlib.pyplot as plt
import networkx
import netgraph
# get edge weights based on edge count
edges = [('a','b'),
('c','d'),
('c','a'),
('a','b'),
('b','a')]
edge_to_count = dict()
for edge in edges:
try:
edge_to_count[edge] += 1.
except KeyError:
edge_to_count[edge] = 1.
# convert to networkx edge list format
edges = [(k[0], k[1], dict(weight=v)) for k, v in edge_to_count.items()]
# create graph
G = nx.DiGraph()
G.add_edges_from(edges)
# draw
netgraph.draw(G, edge_labels=edge_to_count, edge_label_font_size=8)
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.