首页 > 解决方案 > 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)

任何帮助将非常感激!提前致谢!

标签: pythonnetworkxgraphvizpygraphviz

解决方案


由于我没有graphviz_layout安装,并且假设它与其他布局功能类似,我创建了一个带有标准布局功能的测试。可以通过遍历边缘来获得坐标。

以下代码使用列表推导使代码更紧凑。最后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()

结果图


推荐阅读