Search code examples
pythongraphgridnetworkx

How to color a subset of nodes on a lattice using networkX


I would like to color some of the nodes in my graph using NetworkX

Hello, I am using NetworkX to generate a grid of nodes as follows

import networkx as nx  
s = 10
G = nx.grid_graph(dim=[s,s])
nodes = list(G.nodes)
edges = list(G.edges)
p = []
for i in range(0, s):
    for j in range(0, s):
        p.append([i,j])
for i in range(0, len(nodes)):
    G.nodes[nodes[i]]['pos'] = p[i]

pos = {}
for i in range(0, len(nodes)):
        pos[nodes[i]] = p[i]

nx.draw(G, pos)

Here is a picture:

enter image description here

However, I don't know how to color a subset of these nodes using a different color (like red or green). For example, say I want to color the bottom left corner as red and top right corner as red and green, how can I pick out these points and tell python to do so? And is there a way to reduce the size of the node?

Also, is there a better way, rather then using networkx, to do this? My ultimate goal is to draw a lattice of points with different colors.

I'm a novice to programming, so I hope this is a clear question.


Solution

  • Build a list of colors and pass it as node_color parameter to draw:

    # default color
    colors = ['#1f78b4'] * len(G)
    # bottom left node is red
    colors[0] = '#C30000'
    # top right node is green
    colors[-1] = '#00C300'
    # third row (2) from bottom, second column (1) is yellow
    colors[1*s+2] = '#FEEC1E'
    
    nx.draw(G, pos, node_color=colors)
    

    NB. I'm adding an extra example to be more generic.

    Output (with node names):

    networkx grid node color