Set node color based on attribute

Viewed 1987

I built a direct graph with default blue nodes as you can see in the image below.

Each node is an object that was created from the class "Node" and each has the attribute "state", which can have one of the following values: {-1, 0, 1}.

I want to show different node colours on the graph below depending on their respective state value, e.g., -1: red, 0: black and 1: blue.

How should I go about doing this?

Linked nodes

1 Answers

Let's use the following random graph as an example:

G = nx.barabasi_albert_graph(20, 1)

plt.figure(figsize=(12, 8))
pos = nx.spring_layout(G, scale=20, k=3/np.sqrt(G.order()))
nx.draw(G, pos=pos, with_labels=True, k=13.8, node_color='lightgreen', node_size=800)

enter image description here

Say we have the following dictionary mapping state to color, and a set of states which I'll set as node attributes:

color_state_map = {-1: 'red', 0: 'black', 1: 'blue'}

states = np.random.choice([-1,0,1], size=20)
nx.set_node_attributes(G, dict(zip(G.nodes(), states)), 'state')

In order to set a node color according to the states, you can use the node_color parameter in nx.draw to set the corresponding node colors for the graph's G.nodes().

plt.figure(figsize=(12, 8))
nx.draw(G, pos=pos, 
        with_labels=True, 
        k=13.8, 
        node_color=[color_state_map[node[1]['state']] 
                    for node in G.nodes(data=True)], 
        node_size=800,
       font_color='white')
plt.show()

enter image description here

Related