How to set colors for nodes in NetworkX?

PythonNetworkx

Python Problem Overview


I created my graph, everything looks great so far, but I want to update color of my nodes after creation.

My goal is to visualize DFS, I will first show the initial graph and then color nodes step by step as DFS solves the problem.

If anyone is interested, sample code is available on Github

Python Solutions


Solution 1 - Python

All you need is to specify a color map which maps a color to each node and send it to nx.draw function. To clarify, for a 20 node I want to color the first 10 in blue and the rest in green. The code will be as follows:

G = nx.erdos_renyi_graph(20, 0.1)
color_map = []
for node in G:
    if node < 10:
        color_map.append('blue')
    else: 
        color_map.append('green')      
nx.draw(G, node_color=color_map, with_labels=True)
plt.show()

You will find the graph in the attached imageenter image description here.

Solution 2 - Python

Refer to node_color parameter:

nx.draw_networkx_nodes(G, pos, node_size=200, node_color='#00b4d9')

Solution 3 - Python

has been answered before, but u can do this as well:

# define color map. user_node = red, book_nodes = green
color_map = ['red' if node == user_id else 'green' for node in G]        
graph = nx.draw_networkx(G,pos, node_color=color_map) # node lables

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGokhan ArikView Question on Stackoverflow
Solution 1 - PythonAbdallah SobehyView Answer on Stackoverflow
Solution 2 - PythonMontenegrodrView Answer on Stackoverflow
Solution 3 - PythonQasim WaniView Answer on Stackoverflow