在NetworkX

时间:2016-02-19 16:28:37

标签: python algorithm networkx graph-theory dijkstra

我在NetworkX Watts-Strogatz随机生成的图形上运行Dikjstra的最短路径算法,我想要找到路径的边缘,我发现它与其他边缘不同在绘制图表之前。

我的Dijkstra算法返回路径中的节点列表,如下所示:

dijkstra(graph, '5', '67')
['67', '62', '59', '56', '3', '99', '5']

我如何改变这些节点之间边缘的颜色,说蓝色而不是红色?

请注意,图表是随机生成的,因此路径每次都会更改,但它始终会将路径中的节点作为列表输出。

我最初尝试过以下几点:

    for i in range(path.__len__()):
        if i != path.__len__()-1:
            wsGraph.add_edge(path[i], path[i]+1, color='b')

但是这并没有修改边缘,只是添加了看起来像新节点的东西。

1 个答案:

答案 0 :(得分:0)

我发现了这个问题, python networkx - mark edges by coloring for graph drawing,这回答了我的问题。我只需要修改它如下:

for e in wsGraph.edges():
    wsGraph[e[0]][e[1]]['color'] = 'grey'
# Set color of edges of the shortest path to green
for i in range(len(path)-1):
    wsGraph[int(path[i])][int(path[i+1])]['color'] = 'red'
# Store in a list to use for drawing
edge_color_list = [wsGraph[e[0]][e[1]]['color'] for e in wsGraph.edges() ]
nx.draw(wsGraph, node_color='blue', edge_color = edge_color_list,   with_labels = True)
plt.show()

我只需要将路径转换为整数而不是字符。我还改变了节点和非路径边缘的颜色,使其更清晰。

结果图片:

Shortest path between 5 and 13 in a randomly generated 25-node Watts-Strogatz graph using my own Dijkstra's algorithm.