微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python - 从 networkx-graphviz_layout

如何解决Python - 从 networkx-graphviz_layout

我对使用 Networkx 和 pygraphviz 比较陌生(请耐心等待...) 我有一个图表,我使用 Networkx 和 graphviz_layout 对其进行了可视化。

在这一行之后:

pos=graphviz_layout(G,prog='dot')

我在图中检索了 x,y 坐标列表,如下所示:

#coordinates of the nodes
node_x = []
node_y = []
for(node,(x,y)) in pos.items():
    node_x.append(x)
    node_y.append(-y)

有没有办法可以检索图中边的坐标并将其附加到列表中?例如

#coordinates of the edges:
edge_x = []
edge_y = []
#how do i get the edge coordinates set by graphviz_layout here?
     edge_x.append(x0)
     edge_x.append(x1)
     edge_x.append(None)
     edge_y.append(y0)
     edge_y.append(y1)
     edge_y.append(None)

任何帮助将不胜感激!提前致谢!

解决方法

由于我没有安装 graphviz_layout,并且假设它的工作方式与其他布局函数类似,因此我使用标准布局函数创建了一个测试。可以通过循环遍历边缘来获得坐标。

以下代码使用 list comprehension 使代码更加紧凑。最后 plt.plot(edge_x,edge_y) 用于可视化创建的列表。

import networkx as nx
import matplotlib.pyplot as plt

G = nx.complete_graph(20)
pos = nx.circular_layout(G)
node_x = [x for x,y in pos.values()]
node_y = [-y for x,y in pos.values()]

edge_x = [x for n0,n1 in G.edges for x in (pos[n0][0],pos[n1][0],None)]
edge_y = [y for n0,n1 in G.edges for y in (-pos[n0][1],-pos[n1][1],None)]

plt.plot(edge_x,edge_y,color='purple',lw=0.5)
plt.scatter(node_x,node_y,color='crimson',s=50,zorder=3)
plt.gca().set_aspect('equal')
plt.axis('off')
plt.show()

resulting plot

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。