Generating graphviz input using python

By Andreas Wilhelm Apr 1, 2013

In my last pots “Using graphviz to draw graphs”, I talked about how to use graphviz to visualize graphs like the one below.


And today I would like to show you how easy it is to extend your own programs to generate code that could be translated by graphviz to a nice looking graph.

#!/usr/bin/env python
class Graph:
  def __init__(self, label, adjacent):
    self.label = label;
    self.adjacent = adjacent;

  def __str__(self):
    result = "digraph {} {{\n".format(self.label);
    result += "\tnode [shape = circle];\n";

    for i in range(0, len(self.adjacent)):
      for j in range(0, len(self.adjacent)):
        if self.adjacent[i][j] != 0:
          result += "\t{} -> {} [label = \"{}\"];\n".format(i, j, self.adjacent[i][j]);

    result += "}";

    return result;

if __name__ == '__main__':
  graph = [[1, 2, 3],
    [-1, 0, 1],
    [0, -1, -2]]
  print Graph("Test", graph)

And now it is pretty easy to execute the python script and visualize the graph generated by it. Just execute the following two lines within a terminal.

python > test.gv
dot -.jpg test.gv -o testGraph.jpg

This will produce a file test.gv that includes the following lines of code

digraph Test {
node [shape = circle];
  0 -> 0 [label = "1"];
  0 -> 1 [label = "2"];
  0 -> 2 [label = "3"];
  1 -> 0 [label = "-1"];
  1 -> 2 [label = "1"];
  2 -> 1 [label = "-1"];
  2 -> 2 [label = "-2"];

and a *.jpg file named testGraph.jpg that shows the graph above. So you see that it is quite simple to extend your software projects to make use of graphviz. And you are of course not limited to python. The same code could easily be written using C/C++, Java or any other programming language. So give it a try. I would be happy to see some of your own implementations in your preferred programming language.

So until next time, happy coding!

is a Computer Science MSc. interested in hardware hacking, embedded Linux, compilers, etc.