簡體   English   中英

使用邊緣元數據繪制有向圖(使用 Python 中的 NetworkX)

[英]Drawing Directed Graph with Edge meta-data (with NetworkX in Python)

我有一個有向多圖,我想將其表示為帶有邊元數據的(完整)有向圖,這樣如果從節點 A 到節點 B(在原始多圖中)有 e 個邊,那么我將 e 保存為元數據-新(非多)有向圖中邊(A,B)的數據。

我可以按如下方式構建圖表:

DG = nx.complete_graph(node_list, create_using= nx.DiGraph() )

其中 node_list = ['node_A', 'node_B', ....]

我可以使用以下方法添加邊緣:

DG.edges[('node_A', 'node_B')]['edge_count'] = 1

但是我如何使用 draw 命令(很好地)打印這個值呢? 我嘗試了以下

nx.draw(DG, with_labels = True)
plt.show()

但是邊緣值隱藏了; 更重要的是,我需要一種很好的方式來顯示與邊 (A,B) 關聯的元數據,並輕松地將它與邊 (B,A) 區分開來。

您應該能夠執行以下操作:

edge_labels = nx.get_edge_attributes(G,'edge_count')

pos = nx.spring_layout(G)
nx.draw(G, pos = pos, with_labels=True)
nx.draw_networkx_edge_labels(G, pos=pos, edge_labels = edge_labels)
plt.show()

這是一種使用彎曲箭頭來避免標簽重疊的方法

import networkx as nx
import matplotlib.pyplot as plt

G = nx.DiGraph()

G.add_nodes_from(range(4))

G.add_edge(0,1,edge_count = 1)
G.add_edge(1,0,edge_count = 2)
G.add_edge(1,2,edge_count = 2)
G.add_edge(2,3,edge_count = 3)
G.add_edge(3,0,edge_count = 2)

def offset(d, pos, dist = .1):
    for (u,v),obj in d.items():
        par = dist*(pos[v] - pos[u])
        dx,dy = par[1],-par[0]
        x,y = obj.get_position()
        obj.set_position((x+dx,y+dy))

edge_labels = nx.get_edge_attributes(G,'edge_count')
pos = nx.spring_layout(G)
nx.draw(G, pos = pos, with_labels=True, connectionstyle = 'arc3,rad=0.2', node_color = 'orange')
d = nx.draw_networkx_edge_labels(G, pos=pos, edge_labels = edge_labels)
offset(d,pos)
plt.gca().set_aspect('equal')
plt.show()

上述結果:

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM