为NetworkX中的特定边缘着色 [英] Coloring specific edges in NetworkX

查看:652
本文介绍了为NetworkX中的特定边缘着色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在NetworkX Watts-Strogatz随机生成的图形上运行Dikjstra的最短路径算法,并且我想在绘制图形之前对所发现的路径边缘进行着色,使其与其余边缘的颜色有所不同.

I'm running a Dikjstra's shortest path algorithm on a NetworkX Watts-Strogatz randomly generated graph and I want to color the edges of the path I've found differently from the rest of the edges before I draw the graph.

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

My Dijkstra's algorithm returns a list of the nodes in the path as follows:

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

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

How would I go about changing the color of the edges between these nodes to say blue instead of red?

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

Note that the graph is randomly generated so the path changes every time, but it will always output the nodes in the path as a list.

我最初尝试了以下方法:

I initially tried something along the lines of:

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

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

But that didn't modify the edges and instead just added what looked like new nodes.

推荐答案

我发现了这个问题, python networkx-通过为图形绘制着色来标记边缘 ,可以回答我的问题.我只需要对其进行如下修改:

I found this question, python networkx - mark edges by coloring for graph drawing, which sort of answers my questions. I just needed to modify it a little bit as follows:

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()

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

I just needed to convert my path to integers instead of characters. I also changed the colours of the nodes and non-path edges to make it more clear.

结果图片:

这篇关于为NetworkX中的特定边缘着色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆