簡體   English   中英

來自 networkx 的 MultiDiGraph 邊使用 connectionStyle 繪制

[英]MultiDiGraph edges from networkx draw with connectionStyle

是否可以使用connectionstyle在具有不同曲率的相同節點以某種方式繪制不同的邊?

我寫了下面的代碼,但我得到了所有三個邊重疊:

import networkx as nx
import matplotlib.pyplot as plt

G = nx.MultiDiGraph()
G.add_node('n1')
G.add_node('n2')
G.add_edge('n1', 'n2', 0)
G.add_edge('n1', 'n2', 1)
G.add_edge('n1', 'n2', 2)

pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels=True, connectionstyle='arc3, rad = 0.3')

plt.show()

這可以通過使用不同的rad參數繪制每個邊來完成 - 如圖所示。 請注意,我這里的方法使用需要 Python 3.6 的 f 字符串 - 在此之下,您將必須使用不同的方法構建字符串。

代碼:

import networkx as nx
import matplotlib.pyplot as plt

G = nx.MultiDiGraph()
G.add_node('n1')
G.add_node('n2')
G.add_edge('n1', 'n2', rad=0.1)
G.add_edge('n1', 'n2', rad=0.2)
G.add_edge('n1', 'n2', rad=0.3)

plt.figure(figsize=(6,6))

pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos)
nx.draw_networkx_labels(G, pos)

for edge in G.edges(data=True):
    nx.draw_networkx_edges(G, pos, edgelist=[(edge[0],edge[1])], connectionstyle=f'arc3, rad = {edge[2]["rad"]}')

plt.show()

輸出:

在此處輸入圖片說明

我們甚至可以創建一個新函數來為我們執行此操作:

import networkx as nx
import matplotlib.pyplot as plt

def new_add_edge(G, a, b):
    if (a, b) in G.edges:
        max_rad = max(x[2]['rad'] for x in G.edges(data=True) if sorted(x[:2]) == sorted([a,b]))
    else:
        max_rad = 0
    G.add_edge(a, b, rad=max_rad+0.1)

G = nx.MultiDiGraph()
G.add_node('n1')
G.add_node('n2')

for i in range(5):
    new_add_edge(G, 'n1', 'n2')

for i in range(5):
    new_add_edge(G, 'n2', 'n1')

plt.figure(figsize=(6,6))

pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos)
nx.draw_networkx_labels(G, pos)

for edge in G.edges(data=True):
    nx.draw_networkx_edges(G, pos, edgelist=[(edge[0],edge[1])], connectionstyle=f'arc3, rad = {edge[2]["rad"]}')

plt.show()

輸出:

在此處輸入圖片說明

暫無
暫無

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

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