问题
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.
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.
回答1:
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.
Image of result:
来源:https://stackoverflow.com/questions/35510095/coloring-specific-edges-in-networkx