为最短路径提供与图中其余路径不同的颜色

giving the shortest path a different color than the rest in a plot

我正在尝试为最短路径赋予与其余边不同的颜色,但它不起作用,因为所有边都具有相同的颜色

color_list = []
for i in G.edges():
    if i in shortestpath:  # if edges is the shortest path color with red
        color_list.append("red")
    else:  # other wise color green 
        color_list.append("Green")
print('c_list',color_list)
print(shortestpath)
#output:(3, 0, 1)
print(G.edges)
#output:[(0, 1), (0, 3), (1, 2), (2, 3), (3, 4)]

weight=nx.get_edge_attributes(G,'weight')
pos=nx.get_node_attributes(G,'pos')

nx.draw_networkx_edge_labels(G,pos,edge_labels=weight)
nx.draw(G,pos,with_labels=weight)
nx.draw_networkx_edges(G,pos,edge_color=color_list)
plt.show()

所以我想要的输出是路径 (3,0,1) 的颜色不同,如下所示:

假设您已经知道最短路径,您可以使用 nx.draw_networkx_edgesedgelist 属性简单地更改这些边的颜色。

首先,将 shortest_path 元组转换为边列表(元组列表)。

shortestpath = (3, 0, 1)
sp = []
for i in range(0,len(shortestpath)-1):
    sp.append((shortestpath[i],shortestpath[i+1]))
# sp = [(3, 0), (0, 1)]

然后用红色绘制构成最短路径的边:

nx.draw_networkx_edge_labels(G, pos, edge_labels=weight)
nx.draw(G, pos, with_labels=weight)
# painting every edge green
nx.draw_networkx_edges(G, pos, edge_color="green")
# painting specific edges red
nx.draw_networkx_edges(G, pos, edgelist=sp, edge_color="r")
plt.show()

您的代码中的问题是以下语句:

if i in shortestpath

这里 i 可以是一个元组,比如说 (0,1) 并且你试图在 (1, 0, 3) 中搜索它,这将 return false.

你基本上需要检查

  1. 01都存在于最短路径
  2. 两者相邻

这是代码

import networkx as nx
import matplotlib.pyplot as plt


G = nx.Graph()

G.add_edge(0, 1, weight=10)
G.add_edge(2, 1, weight=5)
G.add_edge(3, 2, weight=25)
G.add_edge(0, 3, weight=3)
G.add_edge(4, 3, weight=8)

shortestpath = nx.shortest_path(G, source=1, target=3, weight='weight')

color_list = []
for u, v in G.edges():
    # Check for both cases, i.e. (0, 1) and (1, 0) exist in shortest path
    # Refer : 
    if any([u,v] == shortestpath[i:i+2] for i in range(len(shortestpath) - 1)):  
        color_list.append("red")
    elif any([v,u] == shortestpath[i:i+2] for i in range(len(shortestpath) - 1)):
        color_list.append("red")
    else:  # other wise color green 
        color_list.append("green")
print('c_list',color_list)
print(shortestpath)
#output:(3, 0, 1)
print(G.edges)
#output:[(0, 1), (0, 3), (1, 2), (2, 3), (3, 4)]

weight=nx.get_edge_attributes(G,'weight')
pos=nx.spring_layout(G)

nx.draw_networkx_edge_labels(G,pos,edge_labels=weight)
nx.draw(G,pos,with_labels=weight)
nx.draw_networkx_edges(G,pos,edge_color=color_list)
plt.show()

您可以refer this link了解有关如何同时检查这对元素的成员资格和邻接关系的更多信息。

这里是Google Colab Notebook with the working code.

参考: