我能够使用networkx填充网络图。我的问题是,当我想突出显示图形无法生成的路径(例如最短路径)时,它将返回下面的错误。
nx.draw_networkx_edges(Gr,pos,edgelist=path_edges,edge_color='r',width=10)
File "/usr/local/lib/python3.6/site-packages/networkx/drawing/nx_pylab.py", line 578, in draw_networkx_edges
if not edgelist or len(edgelist) == 0: # no edges!
TypeError: object of type 'zip' has no len()
我寻找解决方案,这是因为脚本在 python3 上运行,因此我收到此错误。解决方案之一是更改并添加列表,如下所示。
原文:
Gr = nx.DiGraph()
edges = graph
Gr.add_edges_from(edges)
pos = nx.spring_layout(Gr)
path = nx.shortest_path(Gr,source=1,target=7)
path_edges = zip(path,path[1:])
nx.draw_networkx_nodes(Gr,pos,nodelist=path,node_color='r')
nx.draw_networkx_edges(Gr,pos,edgelist=path_edges,edge_color='r',width=10)
plt.axis('equal')
plt.show()
修改:
path = nx.shortest_path(Gr,source=1,target=7)
path_edges = list(zip(path,path[1:]))
nx.draw_networkx_nodes(Gr,pos,nodelist=path,node_color='r')
nx.draw_networkx_edges(Gr,pos,edgelist=path_edges,edge_color='r',width=10)
plt.axis('equal')
plt.show()
能够运行脚本,没有错误,并且能够生成图形,但突出显示的路径(红色)未与拓扑节点和链接对齐。红色路径应位于顶部并与节点/路径 1-2-3-4-5-6-7 对齐。请引用下面的图片
请告知如何解决此问题。
最佳答案
我能够使用以下代码生成您想要的图表 - 如果您遇到任何问题,请告诉我。您需要将 zip
对象转换为 list
是正确的,但我认为您的绘图代码中可能还有其他错误。如果您需要 nx.spring_layout
的输出每次都相同,则可以使用 seed
关键字参数,例如 pos = nx.spring_layout(Gr ,种子=123)
。
代码:
import networkx as nx
# Set up graph
Gr = nx.DiGraph()
edges = [(i+1, i+2) for i in range(10)] + [(i+2, i+1) for i in range(10)]
Gr.add_edges_from(edges)
# Get position using spring layout
pos = nx.spring_layout(Gr)
# Get shortest path
path = nx.shortest_path(Gr,source=1,target=7)
path_edges = list(zip(path,path[1:]))
# Draw nodes and edges not included in path
nx.draw_networkx_nodes(Gr, pos, nodelist=set(Gr.nodes)-set(path))
nx.draw_networkx_edges(Gr, pos, edgelist=set(Gr.edges)-set(path_edges), connectionstyle='arc3, rad = 0.3')
# Draw nodes and edges included in path
nx.draw_networkx_nodes(Gr, pos, nodelist=path, node_color='r')
nx.draw_networkx_edges(Gr,pos,edgelist=path_edges,edge_color='r', connectionstyle='arc3, rad = 0.3')
# Draw labels
nx.draw_networkx_labels(Gr,pos)
输出:
关于python - 突出显示 NetworkX 中的某些节点/边 - 使用 zip() 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60164893/