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)
輸出:

添加回答
舉報
