[英]Create graph with curved and labelled edges in Networkx
我目前正在使用nx.draw
顯示有幾個節點和連接它們的邊的有向圖。 邊通過nx.draw_networkx_edge_labels
標記。
現在我想通過設置connectionstyle
來“減輕”圖形的“剛性”方面,它適用於未標記的邊緣。
問題是,如果我顯示標簽,它們的繪制就好像邊緣沒有彎曲一樣,最終會在邊緣和標簽之間產生巨大的偏移。
有沒有辦法解決這個限制? 我找不到nx.draw_networkx_edge_labels
的“偏移”選項來解決這個問題。
編輯:
以上是該問題的一個簡單示例:
import matplotlib.pyplot as plt
import networkx as nx
tab = ("r", ["s", "t", "u", "v", "w", "x", "y", "z"])
producer = tab[0]
consumers = tab[1]
color_map = []
DG = nx.DiGraph()
for i, cons in enumerate(consumers):
DG.add_edge(producer, cons, label=f"edge-{i}")
for i in range(len(DG.nodes())):
if i < 1 + len(consumers):
color_map.append("#DCE46F")
else:
color_map.append("#6FA2E4")
pos = nx.shell_layout(DG)
labels = nx.get_edge_attributes(DG, 'label')
nx.draw(DG, pos, node_color=color_map, connectionstyle="arc3, rad=0.2", with_labels=True, font_size=8, node_size=1000, node_shape='o')
nx.draw_networkx_edge_labels(DG, pos, edge_labels=labels)
plt.show()
電流輸出:
如果您願意使用其他庫進行可視化,我編寫(並維護)了netgraph
。 在netgraph
中,邊緣標簽跟蹤邊緣,即使它們是彎曲的。
import numpy as np
import matplotlib.pyplot as plt
import networkx as nx
from netgraph import Graph # pip install netgraph
tab = ("r", ["s", "t", "u", "v", "w", "x", "y", "z"])
producer = tab[0]
consumers = tab[1]
DG = nx.DiGraph()
for i, cons in enumerate(consumers):
DG.add_edge(producer, cons, label=f"edge-{i}")
node_color = dict()
for node in DG:
if node in producer:
node_color[node] = "#DCE46F"
else:
node_color[node] = "#6FA2E4"
pos = nx.shell_layout(DG)
pos[producer] = pos[producer] + np.array([0.2, 0])
edge_labels = nx.get_edge_attributes(DG, 'label')
Graph(DG, node_layout=pos, edge_layout='curved', origin=(-1, -1), scale=(2, 2),
node_color=node_color, node_size=8.,
node_labels=True, node_label_fontdict=dict(size=10),
edge_labels=edge_labels, edge_label_fontdict=dict(size=10),
)
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.