![](/img/trans.png)
[英]how to draw multigraph in networkx using matplotlib or graphviz
[英]How to label edges of a Multigraph in Networkx and matplotlib?
我有一個無向多圖,我想用標簽繪制邊緣,有什么建議嗎? 我遵循建議,但仍然沒有邊緣標簽。 atomh33ls 使用networkx 在兩個節點之間繪制多條邊
G=nx.MultiGraph ()
G.add_edge(1,2,weight=7)
G.add_edge(1,2,weight=2)
G.add_edge(1,2,weight=3)
G.add_edge(3,1,weight=2)
G.add_edge(3,2,weight=3)
node_label = nx.get_node_attributes(G,'id')
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos, label=node_label)
nx.draw_networkx_labels(G, pos, label=node_label)
edge_labels=nx.get_edge_attributes(G,'weight')
ax = plt.gca()
for e in G.edges:
ax.annotate("",
xy=pos[e[0]], xycoords='data',
xytext=pos[e[1]], textcoords='data',
arrowprops=dict(arrowstyle="-", color="0.5",
shrinkA=5, shrinkB=5,
patchA=None, patchB=None,
connectionstyle="arc3,rad=rrr".replace('rrr',str(0.3*e[2])
),
),
)
#nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
plt.axis('off')
plt.show()
nx.get_edge_attributes
返回的字典具有結構(source, dest, enum):attr
,其中第三個字段僅枚舉每條邊的出現。 這第三個字段是必需的,因為鍵在字典中必須是唯一的。 但是,這意味着它不能在nx.draw_networkx_edge_labels
中使用,因為它需要一個(source, dest):attr
結構化字典。
nx.get_edge_attributes(G,'weight')
# {(1, 2, 0): 7, (1, 2, 1): 2, (1, 2, 2): 3, (1, 3, 0): 2, (2, 3, 0): 3}
所以這真的不適用於MultiGraphs。 遵循與此處相同的想法,您可以做的事情是label
帶有權重值的邊,並使用dot
將圖形導出nx.write_dot
,這將在可視化上使用這些labels
。
感謝@yatu。 這是迄今為止標記的無向多圖的優雅解決方案。 請給我更多改進風格的提示!
import networkx as nx
import matplotlib.pyplot as plt
from IPython.display import Image
G=nx.MultiGraph ()
G.add_edge(1,2,weight=1)
G.add_edge(1,2,weight=2)
G.add_edge(1,2,weight=3)
G.add_edge(3,1,weight=4)
G.add_edge(3,2,weight=5)
for edge in G.edges(data=True): edge[2]['label'] = edge[2]['weight']
node_label = nx.get_node_attributes(G,'id')
pos = nx.spring_layout(G)
node_label = nx.get_node_attributes(G,'id')
pos = nx.spring_layout(G)
p=nx.drawing.nx_pydot.to_pydot(G)
p.write_png('multi.png')
Image(filename='multi.png')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.