gpt4 book ai didi

python - 绘制具有弯曲边的拓扑有序图

转载 作者:行者123 更新时间:2023-12-02 02:49:30 32 4
gpt4 key购买 nike

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

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)

我们可以使用节点名称来定义一个字典,将节点名称映射到一条线,其中 x 坐标与节点名称相同。现在获得具有弯曲边缘的精美布局是棘手的部分。虽然这是必要的,否则边缘会相互重叠。这可以使用 matplotlib.axes.Axes.annotate 来完成.

请注意,我假设源在 even 节点号处的边有一个 符号弧,否则为负,如果不是这种情况,它应该是足够简单以适应:

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

关于python - 绘制具有弯曲边的拓扑有序图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62287492/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com