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:

# -*- coding: utf-8 -*-
pydot example 1
@author: Federico Cáceres
import pydot # import pydot or you're not going to get anywhere my friend 😀
# first you create a new graph, you do that with pydot.Dot()
graph = pydot.Dot(graph_type='graph')
# the idea here is not to cover how to represent the hierarchical data
# but rather how to graph it, so I'm not going to work on some fancy
# recursive function to traverse a multidimensional array…
# I'm going to hardcode stuff… sorry if that offends you
# let's add the relationship between the king and vassals
for i in range(3):
# we can get right into action by "drawing" edges between the nodes in our graph
# we do not need to CREATE nodes, but if you want to give them some custom style
# then I would recomend you to do so… let's cover that later
# the pydot.Edge() constructor receives two parameters, a source node and a destination
# node, they are just strings like you can see
edge = pydot.Edge("king", "lord%d" % i)
# and we obviosuly need to add the edge to our graph
# now let us add some vassals
vassal_num = 0
for i in range(3):
# we create new edges, now between our previous lords and the new vassals
# let us create two vassals for each lord
for j in range(2):
edge = pydot.Edge("lord%d" % i, "vassal%d" % vassal_num)
vassal_num += 1
# ok, we are set, let's save our graph into a file
# and we are done!

view raw

hosted with ❤ by GitHub

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?

# -*- coding: utf-8 -*-
pydot example 2
@author: Federico Cáceres
import pydot
# this time, in graph_type we specify we want a DIrected GRAPH
graph = pydot.Dot(graph_type='digraph')
# in the last example, we did no explicitly create nodes, we just created the edges and
# they automatically placed nodes on the graph. Unfortunately, this way we cannot specify
# custom styles for the nodes (although you CAN set a default style for all objects on
# the graph…), so let's create the nodes manually.
# creating nodes is as simple as creating edges!
node_a = pydot.Node("Node A", style="filled", fillcolor="red")
# but… what are all those extra stuff after "Node A"?
# well, these arguments define how the node is going to look on the graph,
# you can find a full reference here:
# which in turn is part of the full docs in
# neat, huh? Let us create the rest of the nodes!
node_b = pydot.Node("Node B", style="filled", fillcolor="green")
node_c = pydot.Node("Node C", style="filled", fillcolor="#0000ff")
node_d = pydot.Node("Node D", style="filled", fillcolor="#976856")
#ok, now we add the nodes to the graph
# and finally we create the edges
# to keep it short, I'll be adding the edge automatically to the graph instead
# of keeping a reference to it in a variable
graph.add_edge(pydot.Edge(node_a, node_b))
graph.add_edge(pydot.Edge(node_b, node_c))
graph.add_edge(pydot.Edge(node_c, node_d))
# but, let's make this last edge special, yes?
graph.add_edge(pydot.Edge(node_d, node_a, label="and back we go again", labelfontcolor="#009933", fontsize="10.0", color="blue"))
# and we are done
# this is too good to be true!

view raw


hosted with ❤ by GitHub

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")

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!

41 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 ( 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?

    1. I’m glad this was useful for you! Unfortunately I have no experience on boost, sorry I can’t help you on that.

  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 “”, line 33, in plot_graph
    File “/usr/lib/python3/dist-packages/”, line 1809, in
    lambda path, f=frmt, prog=self.prog : self.write(path, format=f, prog=prog))
    File “/usr/lib/python3/dist-packages/”, line 1911, in write
    dot_fd.write(self.create(prog, format))
    File “/usr/lib/python3/dist-packages/”, 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/”, line 32, in
        File “/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/”, 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/”, line 1696, in write
        dot_fd.write(self.create(prog, format))
        File “/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/”, 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 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:

  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.

  11. I am getting this error:
    Traceback (most recent call last):
    File “/root/anaconda3/lib/python3.5/site-packages/”, line 1878, in create
    stderr=subprocess.PIPE, stdout=subprocess.PIPE)
    File “/root/anaconda3/lib/python3.5/”, line 950, in __init__
    restore_signals, start_new_session)
    File “/root/anaconda3/lib/python3.5/”, line 1544, in _execute_child
    raise child_exception_type(errno_num, err_msg)
    FileNotFoundError: [Errno 2] No such file or directory: ‘dot’

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
    File “”, line 19, in
    File “/root/anaconda3/lib/python3.5/site-packages/”, line 1691, in
    self.write(path, format=f, prog=prog))
    File “/root/anaconda3/lib/python3.5/site-packages/”, line 1774, in write
    s = self.create(prog, format)
    File “/root/anaconda3/lib/python3.5/site-packages/”, line 1883, in create
    Exception: “dot” not found in path.

    Could you provide any solution?

    1. Hey Omkar, seems like Python cannot find dot. Pydot is an interface for the program that does the drawing, dot, which is part of Graphviz.

      Depending on how you installed pydot, Graphviz might have not been installed. can you try installing Graphviz and checking if this works?

      If you have already installed Graphviz, you can take a look at this post in Stackoverflow, it lists several solutions for this problem for both Windows and Mac: Why is pydot unable to find GraphViz’s executables in Windows 8?

      Hope this helps!

Leave a Reply

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

You are commenting using your 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 )

Connecting to %s