简体   繁体   中英

NetworkX color the nodes in path

How can I color the nodes in the shortest path (in NetworkX library). I found a way to add nodes in different color, but I don't know how to edit the nodes in random graph. I could imagine it being rather easy, but I could not find this part in the documentation. The code below generates a random graph and should calculate the shortest path, if this works perfectly then all i need is to mark that path somehow.

import networkx as nx
import matplotlib.pyplot as plt

G = nx.fast_gnp_random_graph(20, 0.14, seed="303", directed=False)

shortestPath = nx.shortest_path(G, source=G.nodes()[10], target=G.nodes()[0], weight="10")
node = G.graph.get(0)

print(shortestPath)
nx.draw(G)
plt.savefig("path.png")
plt.show()

You can change the color of the nodes in the graph using networkx.draw_networkx_nodes . You can color nodes diffrerently by providing a list of colors to draw_networkx_nodes , one per node. In your case, you could construct the node_colors list as follows:

node_colors = ["blue" if n in shortestPath else "red" for n in G.nodes()]

Then, you just need to create a layout for your graph (I'm using the spring_layout in this example), and then draw your graph:

pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos=pos, node_color=node_colors)
nx.draw_networkx_edges(G, pos=pos)

图形

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM