突出显示 NetworkX 中的某些节点/边缘 - 使用 zip() 的问题

我能够使用 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 对齐。请参考下面的图片

http://img.mukewang.com/62df572f0001a71904991148.jpg

不负相思意
浏览 96回答 1
1回答

慕仙森

我能够使用以下代码生成您似乎想要的图表 - 如果您遇到任何问题,请告诉我。您需要将zip对象转换为 a是正确的list,但我认为您的绘图代码中可能存在其他错误。nx.spring_layout如果您需要每次的输出都相同,则可以使用seed关键字参数,例如pos = nx.spring_layout(Gr, seed=123).代码:import networkx as nx# Set up graphGr = 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 layoutpos = nx.spring_layout(Gr)# Get shortest pathpath = nx.shortest_path(Gr,source=1,target=7)path_edges = list(zip(path,path[1:]))# Draw nodes and edges not included in pathnx.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 pathnx.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 labelsnx.draw_networkx_labels(Gr,pos)输出:
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python