Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlighting the shortest path in a Networkx graph

I have a network of people. I can display how they are connected by creating a directed graph using Networkx.

Here is a code sample:

edges = edglist
nodes = nodelist
dg.add_weighted_edges_from(edges)
#print dg.nodes()
print nx.shortest_path(dg, source='Freda', target='Levi', weight=None)
nx.draw(dg)
plt.savefig("path.png")

Which produces: connections graph

I can also calculate a shortest path between two nodes. However what I am stuck on is how to highlight this 'shortest path'. Any pointers would be greatly appreciated. BTW, I am a newbie

like image 453
timebandit Avatar asked Jun 03 '14 20:06

timebandit


2 Answers

import matplotlib.pyplot as plt
G = nx.karate_club_graph()
pos = nx.spring_layout(G)
nx.draw(G,pos,node_color='k')
# draw path in red
path = nx.shortest_path(G,source=14,target=16)
path_edges = list(zip(path,path[1:]))
nx.draw_networkx_nodes(G,pos,nodelist=path,node_color='r')
nx.draw_networkx_edges(G,pos,edgelist=path_edges,edge_color='r',width=10)
plt.axis('equal')
plt.show()

enter image description here

like image 72
Aric Avatar answered Sep 20 '22 15:09

Aric


you should add a set() path_edges = set(path_edges)after your zip() to get the shortest path coloration work

like image 29
boumelha adam Avatar answered Sep 21 '22 15:09

boumelha adam