Highlighting the shortest path in a Networkx diagram

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

Here is a sample code:

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

What produces: connections graph

I can also calculate the shortest path between two nodes. However, I am stuck on how to highlight this “shortest path”. Any pointers would be greatly appreciated. BTW, I'm new

+5
source share
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 = 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

+14
source

You must add set () path_edges = set(path_edges)after zip () to get the job of coloring the shortest path

0
source

Source: https://habr.com/ru/post/1543127/


All Articles