如何在最短路径中为节点着色(在NetworkX库中)。我找到了一种添加不同颜色节点的方法,但我不知道如何编辑随机图中的节点。我可以想象它很容易,但我在文档中找不到这一部分。下面的代码生成一个随机图,并应计算最短路径,如果这完全有效,那么我需要的是以某种方式标记该路径。
import networkx as nx
import matplotlib.pyplot as plt
G = nx.fast_gnp_random_graph(20, 0.14, seed="303", directed=False)
shortestPath = nx.shortest_path(G, source=G.nodes()[10], target=G.nodes()[0], weight="10")
node = G.graph.get(0)
print(shortestPath)
nx.draw(G)
plt.savefig("path.png")
plt.show()
答案 0 :(得分:1)
您可以使用networkx.draw_networkx_nodes
更改图表中节点的颜色。您可以通过向draw_networkx_nodes
提供一个颜色列表,每个节点一个颜色,对颜色节点进行颜色校正。在您的情况下,您可以按如下方式构建node_colors
列表:
node_colors = ["blue" if n in shortestPath else "red" for n in G.nodes()]
然后,您只需要为图表创建一个布局(我在本例中使用spring_layout
),然后绘制图表:
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos=pos, node_color=node_colors)
nx.draw_networkx_edges(G, pos=pos)