绘制具有弯曲边的拓扑有序图 [英] Draw topological ordered graph with curved edges

查看:85
本文介绍了绘制具有弯曲边的拓扑有序图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 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坐标与节点名称相同.现在获得带有弯曲边缘的精美布局是棘手的部分.虽然这是必要的,否则边缘会相互重叠.这可以使用

I am trying to draw graph using networks.draw() function in python. I have the edges of the graph in topological sorted order although it is not directed graph. I want to print the graph that looks like a dependency DAG for better visibility. Something like this is the goal:

How should I do this?

解决方案

Using an example edge list as follows, and building an undirected graph:

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)

We can use the node names to define a dictionary mapping a node name to a line, where the x coordinate is the same as the node name. Now getting the fancy layout with the curved edges is the tricky part. Though it is necessary, otherwise the edges will overlap each other. This can be done using matplotlib.axes.Axes.annotate.

Note that I assume edges with a source at an even node number have a positive signed arc, and negative otherwise, if that is not the case, it should be simple enough to adapt:

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

这篇关于绘制具有弯曲边的拓扑有序图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆