Generating Graph Visualizations with pydot and Graphviz


Hi, for my latest college assignment I had to find a way to visualize data that is interrelated. For instance, my application generated the following data:

A --> B
B --> C
B --> D

And I needed a way to generate pretty graphs without too much headache!

I am already using wxPython for the application’s UI (it saved me a lot of time, and I learned a lot in the process, even implemented my own clone of the Aero Wizard layout used in Windows Vista and 7), so I tried to look for a way to integrate some other super powered library into my app. I quickly remembered a couple of projects that used Graphviz to generate visualizations of Django model definitions: DjangoGraphviz, and django-graphviz. I even hacked one of them to generate visualizations where each app had it’s own color. But these were complicated projects, because they generated some funky XML (correct me if I’m wrong) files that where later fed to graphviz and you had to mess a little with config options.

I wanted something simpler… lucky me, I stumbled into the wonderful project pydot. It was just what I needed, after a couple of experiments I could quickly generate “fantastic” visualizations with almost no extra effort. I’m using this on my Fedora 11 x86_64 box, so I just had to install pydot and easy_install handled the dependencies (it automatically downloaded and installed pyparsing), I am not sure what the requirements for Windows are… specially to get this running with py2exe, I’ll be blogging about that later.

In any case, let me provide you with a quick “getting started” tutorial guide on how this works.

Example 1: “Easy as Pie”

Ok, let’s try an easy one, suppose you have a set of data that you want to represent in a hierarchical way… Say: King, Lords and Vassals… Let’s try to graph that with as little code as we can:

Simple, huh? You should have a graph like this:

Graph generated by example 1
Graph generated by example 1

Now… that looks pretty boring, right? Let’s try something some more… colorful and with a different kind of graph.

Example 2: “Still Easy as Pie”

Ok, on the last example we made an undirected graph, let’s create a directed one now, and let’s also add some colors and labels on the edges between nodes. Say we have four nodes: A, B, C and D, were A points to B, B points to C, C points to D and D points back to A… let’s try that, ok?

That code generates this graph:

Graph generated in example 2
Graph generated in example 2

As you can see, the possibilities are endless, using the attributes you can set for each node, edge and other forms supported by the library, you can easily visualize your data that would otherwise be very hard to see.

One more thing, you can set the attributes when initializing the Node/Edge, or you can use the set_xyz method, for instance, instead of doing this:

pydot.Edge(node_d, node_a, label="and back we go again", labelfontcolor="#009933", fontsize="10.0", color="blue")

You could do this:

edge = pydot.Edge(node_d, node_a)
edge.set_label("and back we go again")
edge.set_labelfontcolor("#009933")
edge.set_fontsize("10.0")
edge.set_color("blue")

That can come in handy.

Well, I hope you found this useful as I have, and that this mini pydot tutorial helps you with this great library.

Don’t forget to visit these links:

Till next time!

37 thoughts on “Generating Graph Visualizations with pydot and Graphviz

    1. Indeed, it is both fun and informative! It’s always easier to see problems in your design when it is displayed in graphs. You should check out those two projects I mentioned at the beginning of the post. I’m not sure if the are the same… or if one is the fork of another…. or if they are completely different, but I remember I used django-graphviz and it was excellent, it worked really well!

  1. Thanks a lot!
    It was not being easy for me to understand how to work with pydot, but after reading your post everything is clear🙂

  2. Federico … Is there a way to visualize the graph without saving it as a png file? In other words, can we use a GUI libraries like wx to read and display the graph from main memory? Thanks, Raj

    1. Hi Raj, I made an app with wxpython and pydot that “drew” graphs in realtime according to a grid that the user can use to model the graph (http://code.google.com/p/pyflowuca/). Unfortunately the source code is in spanish, but let me tell you how I did it. I just created the graphs on a temporary file using python’s tempfile module and loaded the file using wxPython bitmap loading functions. Just remember to delete the file once you’re done.

  3. Cool, looking at directive graphs in Python right now, the python-graph looks good but couldnt get it working with the brief amount of time spent today. This pydot seems to work out of the box, sweet.

    Did you ever get this runing with py2exe??

    1. Hi Alan, pydot is indeed very simple to get working and use. I don’t remember having to do anything special to make pydot work with py2exe, did you get it working?

  4. Hi Federico,

    I can build to .exe but it still requires the Graphviz.exe.

    All the libs I have seen (pydot, pygraphviz) all need Graphviz installed on the computer. The issue I am having is directing Pydot or PyGraphviz to the relevant DLL’s which Py2exe pulls out correctly.

    For example when I use PyGraphviz it references the Graphviz exe’s through an import _graphviz (which is .pyd file that calls the Graphviz .exe’s).

    Still digging… in essence I would of thought that there was simple Pyhon libs to go from .dot to .svg without this Graphviz?? Also seen WinGraphviz.dll which I think is independant of Graphviz, just need to figure out how to use it.

  5. Thank you very much. This got me up and running with pydot in about 10 min. The one thing I didn’t do was have GraphViz installed before trying to run the code. After installing GraphViz it on Win 7 x64, it was smooth sailing.

  6. is there any way to use pyDot to create a tree and then build a GUI application in wx using the nodes in the tree as widgets?

  7. I am getting this error : File “introspect.py”, line 33, in plot_graph
    graph.write_jpeg(‘example.jpeg’)
    File “/usr/lib/python3/dist-packages/pydot.py”, line 1809, in
    lambda path, f=frmt, prog=self.prog : self.write(path, format=f, prog=prog))
    File “/usr/lib/python3/dist-packages/pydot.py”, line 1911, in write
    dot_fd.write(self.create(prog, format))
    File “/usr/lib/python3/dist-packages/pydot.py”, line 2003, in create
    stdout_output = ”.join(stdout_output)
    TypeError: sequence item 0: expected str instance, bytes found

    1. Hi,

      These examples were built with Python 2 in mind, and you seem to be using Python 3, so I am afraid I cannot assist you debugging this issue. The error tells me this might be an issue with data types… I hope you got it fixed.

      1. Federico, firstly thank you for the great source.
        I’m developing a solution that build graphs as well and when tried to run your code I got the same error, in python 2:

        Couldn’t import dot_parser, loading of dot files will not be possible.
        Traceback (most recent call last):
        File “/Users/zallaricardo/Documents/Python/graph_test.py”, line 32, in
        graph.write_png(‘example1_graph.png’)
        File “/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pydot.py”, line 1602, in
        lambda path, f=frmt, prog=self.prog : self.write(path, format=f, prog=prog))
        File “/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pydot.py”, line 1696, in write
        dot_fd.write(self.create(prog, format))
        File “/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pydot.py”, line 1796, in create
        status, stderr_output) )
        pydot.InvocationException: Program terminated with status: -5. stderr follows: dyld: Library not loaded: /usr/lib/libltdl.7.dylib
        Referenced from: /usr/local/bin/dot
        Reason: image not found

        Would you have any hint to fix it?

  8. This is the clearest explanation of use of the graphviz and pydot libraries that I have found to date. Kudos to the clarity and simplicity of your explanation. Big help with helping me diagram the system architecture of a web project for a recent Python Programmmig course that I’m enrolled. Well done!

  9. Another way to fix your first issue with “_noncomma” is to change pydot’s dot_parser.py file so that the private _noncomma variable can be seen

    Change this one line:

    ParseException, ParseResults, CharsNotIn, _noncomma, dblQuotedString, QuotedString, ParserElement )

    To these two lines:

    ParseException, ParseResults, CharsNotIn, dblQuotedString, QuotedString, ParserElement )

    _noncomma = “”.join( [ c for c in printables if c != “,” ] )

    This answer comes from one the answers (which did not get voted as **the** answer) here:
    http://stackoverflow.com/questions/15951748/pydot-and-graphviz-error-couldnt-import-dot-parser-loading-of-dot-files-will

  10. Exception: “dot.exe” not found in path. is the error i am getting while running this graph. please help me with this

    1. Hi!

      I don’t know which version of Windows you’re running, but first I would suggest that you make sure that you have installed Graphviz and pydot.

      If you have, then this link on stack overflow seems to be relevant:
      Why is pydot unable to find GraphViz’s executables in Windows 8?

      It seems that you either need to install them in a specific order (first Graphviz and then pydot) or add Graphviz binaries directory manually to your PATH, check the answers in that post and see what works for you.

      Let us know what worked and, if you can, +1 the answer that worked for you so that others can also benefit.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s