Search code examples
pythoncolorsgraphviz

Set custom node color using Python Graphviz package


The graphviz Python package allows setting the color of a node to be a string argument.

from graphviz import Digraph

g = Digraph('example_graph')
g.node('Test Node', color='green')

I would like to specify a color that uses a precise numerical encoding such as RGB or hexcodes. If I try the following

from graphviz import Digraph

g = Digraph('example_graph')
g.node('Test Node', color=(50, 50, 50))

I get the error:

TypeError: expected string or bytes-like object

Similarly I tried setting the tuple to be a string:

from graphviz import Digraph

g = Digraph('example_graph')
g.node('Test Node', color='(50, 50, 50)')

which resulted in this warning and the diagram seems to default to black.

Warning: (50, 50, 50) is not a known color.

It isn't clear to me what possible arguments are allowed, and searching the documents for 'color' did not reveal any examples other than simple named colors.

Is this possible with the graphviz Python package, or can it only take a small selection of named colors?


Solution

  • I raised a Github issue with the package maintainers. They were kind enough to add a colors.py example to their documentation.

    One approach from their examples using RGB is the following.

    import graphviz
    
    g = graphviz.Graph('colors')
    
    g.node('RGB: #40e0d0', style='filled', fillcolor='#40e0d0')
    
    g.view()