根据 Dijkstra 算法访问的边更改 NetworkX Graph 中的边颜色

Change Edge color in NetworkX Graph depending on what edges has been visisted by Dijkstras algorithm

我正在尝试更改 python 包 NetworkX 中 dijkstras 算法访问的节点之间边的颜色。该项目中使用的图表是内置的 nx.karate_club_graph()

如果我有它的代码,预期结果是被访问节点之间的边的颜色将是红色。当前结果是所有访问过的节点都高亮显示,但边缘是默认的黑色。

我从堆栈溢出中查看了关于改变边缘颜色的不同解决方案,但我无法让它们适用于我的特定场景。

这是我编写的代码。

import networkx as nx
import matplotlib.pyplot as plt
G = nx.karate_club_graph()

nodes = G.nodes()

position = nx.spring_layout(G)
color = {"Mr. Hi": "#3DA3F5", "Officer": "#E0D91B"}
dijkstra_route = nx.dijkstra_path(G, 24, 16)
colors = ["red" if n in dijkstra_route else color[G.nodes[n]["club"]] for n in nodes] 
nx.draw(G, position, node_color = colors, with_labels = True)

尝试将 edge_color 添加到 nx.draw()

import networkx as nx
import matplotlib.pyplot as plt

G = nx.karate_club_graph()

nodes = G.nodes()

position = nx.spring_layout(G)
color = {"Mr. Hi": "#3DA3F5", "Officer": "#E0D91B"}
dijkstra_route = nx.dijkstra_path(G, 24, 16)

colors = ["red" if n in dijkstra_route else color[G.nodes[n]["club"]] for n in nodes]

dijkstra_edges = []
for index in range(0, len(dijkstra_route) - 1):
   edge = (dijkstra_route[index], dijkstra_route[index + 1])
   dijkstra_edges.append(edge)

edge_colors = ["red" if edge in dijkstra_edges else "black" for edge in G.edges()]


nx.draw(G, position, node_color=colors, edge_color=edge_colors, with_labels=True)
plt.show()

显示 this,这与您想要的很接近,但我不明白为什么边 (31,0) 没有着色