绘制具有弯曲边的拓扑有序图
Draw topological ordered graph with curved edges
我正在尝试使用 python 中的 networks.draw() 函数绘制图形。尽管它不是有向图,但我具有按拓扑排序顺序排列的图的边。我想打印看起来像依赖 DAG 的图形以获得更好的可见性。目标是这样的:
我应该怎么做?
使用如下示例边列表,并构建无向图:
edges = [[1,3], [1,4], [1,5], [5,7], [5,8] ,[5,9],
[9,11], [9,12], [9,13], [2,4], [6,8] ,[10,12]]
G = nx.Graph()
G.add_edges_from(edges)
我们可以使用节点名称来定义一个字典,将节点名称映射到一条线,其中x
坐标与节点名称相同。现在获得具有弯曲边缘的精美布局是棘手的部分。虽然这是必要的,否则边缘会相互重叠。这可以使用 matplotlib.axes.Axes.annotate
来完成。
请注意,我假设源位于 even 节点号的边具有 positive 符号弧,否则为负,如果不是这样的,适应起来应该很简单:
pos = {node:(node,0) for node in G.nodes()}
plt.figure(figsize=(15,5))
ax = plt.gca()
for edge in edges:
source, target = edge
rad = 0.8
rad = rad if source%2 else -rad
ax.annotate("",
xy=pos[source],
xytext=pos[target],
arrowprops=dict(arrowstyle="-", color="black",
connectionstyle=f"arc3,rad={rad}",
alpha=0.6,
linewidth=1.5))
nx.draw_networkx_nodes(G, pos=pos, node_size=500, node_color='black')
nx.draw_networkx_labels(G, pos=pos, font_color='white')
plt.box(False)
plt.show()
我正在尝试使用 python 中的 networks.draw() 函数绘制图形。尽管它不是有向图,但我具有按拓扑排序顺序排列的图的边。我想打印看起来像依赖 DAG 的图形以获得更好的可见性。目标是这样的:
我应该怎么做?
使用如下示例边列表,并构建无向图:
edges = [[1,3], [1,4], [1,5], [5,7], [5,8] ,[5,9],
[9,11], [9,12], [9,13], [2,4], [6,8] ,[10,12]]
G = nx.Graph()
G.add_edges_from(edges)
我们可以使用节点名称来定义一个字典,将节点名称映射到一条线,其中x
坐标与节点名称相同。现在获得具有弯曲边缘的精美布局是棘手的部分。虽然这是必要的,否则边缘会相互重叠。这可以使用 matplotlib.axes.Axes.annotate
来完成。
请注意,我假设源位于 even 节点号的边具有 positive 符号弧,否则为负,如果不是这样的,适应起来应该很简单:
pos = {node:(node,0) for node in G.nodes()}
plt.figure(figsize=(15,5))
ax = plt.gca()
for edge in edges:
source, target = edge
rad = 0.8
rad = rad if source%2 else -rad
ax.annotate("",
xy=pos[source],
xytext=pos[target],
arrowprops=dict(arrowstyle="-", color="black",
connectionstyle=f"arc3,rad={rad}",
alpha=0.6,
linewidth=1.5))
nx.draw_networkx_nodes(G, pos=pos, node_size=500, node_color='black')
nx.draw_networkx_labels(G, pos=pos, font_color='white')
plt.box(False)
plt.show()