I generated a graph with networkx
JavaScript
x
18
18
1
import networkx as nx
2
s = 5
3
G = nx.grid_graph(dim=[s,s])
4
nodes = list(G.nodes)
5
edges = list(G.edges)
6
p = []
7
for i in range(0, s):
8
for j in range(0, s):
9
p.append([i,j])
10
for i in range(0, len(nodes)):
11
G.nodes[nodes[i]]['pos'] = p[i]
12
13
pos = {}
14
for i in range(0, len(nodes)):
15
pos[nodes[i]] = p[i]
16
17
nx.draw(G, pos)
18
Now I would like to assign a value to each node between 0
and 4
JavaScript
1
5
1
from random import randint
2
val = []
3
for i in range(0, len(G.nodes())):
4
val.append(randint(0,4))
5
And I would like to assign the color to each node base on the val
list and plot something like shown here
Advertisement
Answer
To set a node property, you can use:
JavaScript
1
2
1
nx.set_node_attributes(G, val, 'val')
2
Networkx draw calls down to draw_networkx_nodes, this takes a cmap and color list, so all you would have to do would be something like:
JavaScript
1
2
1
nx.draw(G, pos, node_color = nx.get_node_attributes(G,'val'), vmin=0, vmax=4, cmap = plt.cm.get_cmap('rainbow'))
2