Search code examples
pythonnumpynetworkx

Changing the colors of nodes based on certain values in Networkx


I have a set of nodes with an adjacency matrix. I want to color these nodes based on the array P such that node 1 = P[0], node 2 = P[1], node 3 = P[2] and so on with a colorbar showing the range of values. The current and expected outputs are presented.

import numpy as np
import networkx as nx

G = nx.grid_2d_graph(3,3)
new_nodes = {e: n for n, e in enumerate(G.nodes, start=1)}
new_edges = [(new_nodes[e1], new_nodes[e2]) for e1, e2 in G.edges]
G = nx.Graph()
G.add_edges_from(new_edges)
nx.draw(G, with_labels=True)

A1 = nx.adjacency_matrix(G) 
A=A1.toarray()
print([A]) 

P=np.array([10.5,20.7,30.7,40.1,50.6,60.3,70.6,80.9,90.8])

The current output is

enter image description here

The expected output is

enter image description here


Solution

  • If you want to color your nodes, you can pass to the draw function a list of color to bind to each nodes. Those color can be computed as hexa decimal values from any range you decided to target. In my proposition below : your P vector holds values between 0 and 100, while color values can be beteween 0 and 255, coded in hexadecimal.

    Proposition:

    P=np.array([10,20,30,40,50,60,70,80,90])
    color_hex_values = [ hex(int(e*255/100))[2:] for e in P ]
    print(color_hex_values)
    nx.draw(G, with_labels=True,node_color=[f"#00{hv}00" for hv in color_hex_values] )