在 Networkx 中创建具有弯曲和标记边的图形

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()