Search code examples
pythonmatplotlibnetworkxdrawtransparency

Transparant, and coloured, networkx nodes with a node colour dictionary?


Whilst drawing a networkx graph, with differently coloured nodes, I'm trying to make some of them transparent. Based on the last answer in this post, that seems to be possible. However, I am experiencing some difficulties in setting both the colour, and the transparency value.

Analog to the given answer in the linked post, I tried:

for node_name in G.nodes:
    if node_name[:4] == "red_":
        colour_dict[node_name] = ["olive",0.5]
    else:
        colour_dict[node_name] = ["yellow",1]
nx.draw(
        G,
        nx.get_node_attributes(G, "pos"),
        with_labels=True,
        node_size=160,
        font_size=6,
        width=0.2,
        node_color=color_map,
        edge_color=edge_color_map,
        # **options,
    )

Which returns:

ValueError: 'c' argument must be a color, a sequence of colors, or a sequence of numbers, not [['olive', 1], ['olive', 1], ['olive', 1], ['olive', 1], ['olive', 1], ['olive', 1], ['olive', 1], ['olive', 1], ['olive', 1], ['olive', 1], ['olive', 1], ['olive', 1], ['olive', 1], ['olive', 1], ['olive', 1], ['olive', 1], ['olive', 1], ['olive', 1]]

Hence, I would like to ask, how can one set the node colour and make it transparent (e.g. 50% transparent) at the same time?


Solution

  • Two alternatives to the method you've chosen are described below:

    1. Rather than searching for rgb values for your desired colors, you could use the method shown in this answer to get the rgb value of the named color (just use colors.to_rgb() instead of colors.to_rgba() though), then append your desired alpha value to the end of the tuple using the method described in this answer.

    2. It may be more convenient to draw the nodes separately using nx.draw_networkx_nodes By doing so, you can pass in a list of colors to node_color and a list of alpha values to alpha. With the colour_dict that you've defined, you can easily create these lists to pass into the drawing function. You can find more details in this question and answer if you'd like.