Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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,20,30,40,50,60,70,80,90])

The current output is

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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] )
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading