亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

突出顯示 NetworkX 中的某些節點/邊緣 - 使用 zip() 的問題

突出顯示 NetworkX 中的某些節點/邊緣 - 使用 zip() 的問題

不負相思意 2022-07-26 10:53:06
我能夠使用 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 = graphGr.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 對齊。請參考下面的圖片
查看完整描述

1 回答

?
慕仙森

TA貢獻1827條經驗 獲得超8個贊

我能夠使用以下代碼生成您似乎想要的圖表 - 如果您遇到任何問題,請告訴我。您需要將zip對象轉換為 a是正確的list,但我認為您的繪圖代碼中可能存在其他錯誤。nx.spring_layout如果您需要每次的輸出都相同,則可以使用seed關鍵字參數,例如pos = nx.spring_layout(Gr, seed=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)

輸出:

http://img1.sycdn.imooc.com//62df573e00014e3b05140336.jpg

查看完整回答
反對 回復 2022-07-26
  • 1 回答
  • 0 關注
  • 127 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號