4

I would like to color the nodes in my graph by the value of a node attribute, and for a specific value of an attribute, I would like to apply a gradient. This is different from the (many!) other responses that I have seen, that aim to add color to a node from a matplotlib cmap (e.g. cmap = plt.get_cmap('Greens')) for all the nodes in a graph. I would like to apply one color to one type of node, and a color map to another type of node.

Here is what I have tried so far. I think this is failing because I'm trying to add a string (e.g. 'yellow') and rgba values (e.g. cmap(dict_1[node])) to color_map, which I then use for the node_color parameter of nx.draw().

import networkx as nx
import matplotlib.pyplot as plt

color_map = []
cmap = plt.get_cmap('Greens')

for node in g:
    if node in list_1:
        color_map.append('yellow')
    elif node in list_2:
        rgba = cmap(dict_1[node])
        color_map.append(rgba*-1)

nx.draw(g, node_color = color_map, node_size = 75)

The color_map method works just fine when I only add colors by name to the color_map, but not in the current form.

Nate
  • 2,113
  • 5
  • 19
  • 25

1 Answers1

6

Well, I found the solution.

I found help here, here, and here.

I changed the elif statement to use the new function I modified: convert_to_hex, and I put the output into the color_map - and it works as expected.

def convert_to_hex(rgba_color) :
    red = int(rgba_color[0]*255)
    green = int(rgba_color[1]*255)
    blue = int(rgba_color[2]*255)
    return '#%02x%02x%02x' % (red, green, blue)

import networkx as nx
import matplotlib.pyplot as plt

color_map = []
cmap = plt.get_cmap('Greens')

for node in g:
    if node in list_1:
        color_map.append('yellow')
    elif node in list_2:
        rgba = cmap(dict_1[node])
        color_map.append(convert_to_hex(rgba))


nx.draw(g, node_color = color_map, node_size = 75)
Community
  • 1
  • 1
Nate
  • 2,113
  • 5
  • 19
  • 25