用曲线边绘制拓扑有序图

2024-04-25 05:08:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用python中的networks.draw()函数绘制图形。图的边是按拓扑排序的,尽管它不是有向图。我想打印看起来像依赖DAG的图形,以获得更好的可见性。目标是这样的:

Graph

我该怎么做


Tags: 函数图形目标排序绘制dagdrawnetworks
1条回答
网友
1楼 · 发布于 2024-04-25 05:08:29

使用如下示例边列表,并构建无向图:

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坐标与节点名相同。现在,获得具有弯曲边缘的奇特布局是一个棘手的部分。尽管这是必要的,否则边缘将相互重叠。这可以使用^{}完成

请注意,我假设源位于偶数节点编号的边具有符号弧,否则为负,如果不是这种情况,则应足够简单以适应:

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

enter image description here

相关问题 更多 >