Search code examples
pythongraphviz

Graphviz/Python: Recoloring a single node after it has been generated


I am getting acquainted with graphviz within Python 2.7. Is it possible to change the properties of a single node after it has been drawn?

e.g.

from graphviz import Digraph
q = Digraph()
q.node('a')
q.node('b')
q.edge('a','b')

q

Output of simple graph

Is it possible to change the color of node 'b' after the fact? I am aware that I can set it at the time of generation by

q.node('b', color = 'blue')

But, I'd like to be able to change it after generating it.

This link Color a particular node in Networkx and Graphviz

suggests using the graph's .node property to update a dict

G.node[2]['fillcolor']='red'

By analogy, I tried

q.node['b']['color'] = 'blue'

which gives an error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-54-43b05071d09a> in <module>()
----> 1 q.node['b']['color'] = 'blue'

TypeError: 'instancemethod' object has no attribute '__getitem__'

I think this may be because I am not using networkx as in the previous case.

I've also read the graphviz docs at http://graphviz.org/content/attrs but none of my experiments have worked. I'm sure it is something straightforward but I am missing it...

--- Old Guy In The Club


Solution

  • I've read through the API docs and don't think it's possible to edit a node after construction.

    If you don't want to use networkx, one workaround would be to store the graph in your own data structure and use that to create the graphviz graph at the point when you're ready to (re-)render it. For example, you could keep a list of the names of all the nodes that should be blue, and then refer to that at the point of constructing your graphviz graph. Separating the model from its rendering in this way might also lead to easier maintenance.