LinuxDevCenter.com

oreilly.comSafari Books Online.Conferences.

We've expanded our Linux news coverage and improved our search! Search for all things Linux across O'Reilly!

Search
Search Tips

advertisement

Listen Print Discuss Subscribe to Linux Subscribe to Newsletters

An Introduction to GraphViz and dot
Pages: 1, 2

Basic Concepts of dot

A generic dot graph is composed of nodes and edges. Our hello.dot example contains a single node and no edges. Edges enter in the game when there are relationships between nodes, for instance hierarchical relationships as in this example, which produced Figure 3:



digraph simple_hierarchy {

B [label="The boss"]      // node B
E [label="The employee"]  // node E

B->E [label="commands", fontcolor=darkgreen] // edge B->E

}

a hierarchical relationship
Figure 3. A hierarchical relationship

dot is especially good at drawing directed graphs, where there is a natural direction. (GraphViz also includes the similar neato tool to produce undirected graphs). In this example the direction is from the boss, who commands, to the employee, who obeys. Of course dot gives you the freedom to revert social hierarchies, as seen in Figure 4:

digraph revolution {

B [label="The boss"]      // node B
E [label="The employee"]  // node E

B->E [label="commands", dir=back, fontcolor=red]  
// revert arrow direction 

}

an inverted hierarchy
Figure 4. An inverted hierarchy

Sometimes, you want to put things of the same importance on the same level. Use the rank option, as in the following example, which describes a hierarchy with a boss, two employees, John and Jack, of the same rank, and a lower ranked employee Al who works for John. See Figure 5 for the results.

digraph hierarchy {

nodesep=1.0 // increases the separation between nodes

node [color=Red,fontname=Courier]
edge [color=Blue, style=dashed] //setup options

Boss->{ John Jack } // the boss has two employees

{rank=same; John Jack} //they have the same rank

John -> Al // John has a subordinate 

John->Jack [dir=both] // but is still on the same level as Jack
}

a multi-level organizational chart
Figure 5. A multi-level organizational chart

This example shows a nifty feature of dot: if you forget to give explicit labels, it will use the name of the nodes as default labels. You can also set the default colors and style for nodes and edges respectively. It is even possible to control the separation between (all) nodes by tuning the nodesep option. I'll leave it as an exercise for the reader to see what happens without the rank option (hint: you get a very ugly graph).

dot is quite sophisticated, with dozen of options which you can find in the excellent documentation. In particular, the man page (man dot) is especially useful and well done. The documentation also explains how to draw graphs containing subgraphs. However, those advanced features are outside the scope of this brief article.

We'll discuss another feature instead: the ability to generate output in different formats. Depending on your requirements, different formats can be more or less suitable. For the purpose of generating printed documentation, the PostScript format is quite handy. On the other hand, if you're producing documentation to convert to HTML format and put on a Web page, PNG format can be handy. It is quite trivial to select an output format with the -T output format type flag:

$ dot hello.dot -Tpng -o hello.png

There are many others available formats, including all the common ones such as GIF, JPG, WBMP, FIG and more exotic ones.

Generating dot Code

dot is not a real programming language, but it is pretty easy to interface dot with a real programming language. Bindings exist for many programming languages—including Java, Perl, and Python. A more lightweight alternative is just to generate the dot code from your preferred language. Doing so will allow you to automate the entire graph generation.

Here is a simple Python example using this technique. This example script shows how to draw Python class hierarchies with the least effort; it may help you in documenting your code.

# dot.py 

"Require Python 2.3 (or 2.2. with from __future__ import generators)"

def dotcode(cls):
    setup='node [color=Green,fontcolor=Blue,fontname=Courier]\n'
    name='hierarchy_of_%s' % cls.__name__
    code='\n'.join(codegenerator(cls))
    return "digraph %s{\n\n%s\n%s\n}" % (name, setup, code)

def codegenerator(cls):
    "Returns a line of dot code at each iteration."
    # works for new style classes; see my Cookbook
    # recipe for a more general solution
    for c in cls.__mro__:
        bases=c.__bases__
        if bases: # generate edges parent -> child
            yield ''.join([' %s -> %s\n' % ( b.__name__,c.__name__)
                           for b in bases])
        if len(bases) > 1: # put all parents on the same level
            yield " {rank=same; %s}\n" % ''.join(
                ['%s ' % b.__name__ for b in bases])

if __name__=="__main__": 
    # returns the dot code generating a simple diamond hierarchy
    class A(object): pass
    class B(A): pass
    class C(A): pass
    class D(B,C): pass
    print dotcode(D)

The function dotcode takes a class and returns the dot source code needed to plot the genealogical tree of that class. codegenerator generates the code, traversing the list of the ancestors of the class (in the Method Resolution Order of the class) and determining the edges and the nodes of the hierarchy. codegenerator is a generator which returns an iterator yielding a line of dot code at each iteration. Generators are a cool recent addition to Python; they come particularly handy for the purpose of generating text or source code.

The output of the script is the following self-explanatory dot code:

digraph hierarchy_of_D {

node [color=Green,fontcolor=Blue,font=Courier]

 B -> D
 C -> D

 {rank=same; B C }

 A -> B

 A -> C

 object -> A

}

Now the simple one-liner:

$ python dot.py | dot -Tpng -o x.png

generates Figure 6.

a Python class diagram
Figure 6. A Python class diagram

References

You may download dot and the others tool coming with GraphViz at the official GraphViz homepage. You will also find plenty of documentation and links to the mailing list.

Perl bindings (thanks to Leon Brocard) and Python bindings (thanks to Manos Renieris) are available. Also, Ero Carrera has written a professional-looking Python interface to dot.

The script dot.py I presented in this article is rather minimalistic. This is on purpose. My Python Cookbook recipe, Drawing inheritance diagrams with Dot, presents a much more sophisticated version with additional examples.

Michele Simionato is employed by Partecs, an open source company headquartered in Rome. He is actively developing web applications in the Zope/Plone framework.


Return to the LinuxDevCenter.com.


Have a question about the examples or what else is possible? Ask Michele here.
You must be logged in to the O'Reilly Network to post a talkback.
Post Comment
Full Threads Oldest First

Showing messages 1 through 10 of 10.

  • modifying graphs
    2007-12-01 09:56:51  rachellee [Reply | View]

    How can I modify the node properties (in particular, color) once I've already defined the graph (in networkx or in graphviz)?

    Thanks,
    Rachel
  • Using dot with Java
    2007-07-04 10:40:56  lite_blue [Reply | View]

    I am here:
    http://www.linuxdevcenter.com/pub/a/linux/2004/05/06/graphviz_dot.html?page=2

    Would you please provide me with Java instructions to produce a good result of one of the examples in "An Introduction to GraphViz and dot - " Thanks. Mike
  • java
    2005-10-19 23:12:20  paint [Reply | View]

    you said that you can generate dot code from your preferred language. Can you show an example for java or refer me to a tutorial. For example, how would create a dot file from helloWorld.java


    • java
      2005-10-28 00:39:12  michelesimionato [Reply | View]

      Just Google for "Graphviz Java" and you will have
      plenty of answers.
  • Dot
    2004-05-23 23:35:11  glenlow [Reply | View]

    The Mac OS X version of Graphviz currently has much better antialiasing of bitmaps; try running some of your dot files through it to see. It is independent of X11 and uses the native font and PDF machinery on that platform.

    It also has a pretty interactive front end, you can tweak most command-line parameters or edit the file, and see the results re-rendered almost instantaneously.

    The sources for the front end are BSD and are available from www.graphviz.org. Perhaps some brave soul can port it to GnuStep or something.

    [BTW, I'm the author of the Mac OS X port.]

    Cheers,
    Glen Low, Pixelglow Software
    www.pixelglow.com
  • Licensing
    2004-05-11 21:05:21  tom_hoffman [Reply | View]

    Unless I'm on drugs, GraphViz has its own slightly ATT lawyer damaged license, which doesn't fit the official open source definition or the Debian definiton of free software. Which is no skin off my nose personally, but I started a little tempest with a purist last week when I contributed a dot generating utility to a GNU licensed project I work with.

    Just something to be aware of.
  • Autodia and other software
    2004-05-11 05:24:15  teejay [Reply | View]

    Michele,


    You seem to have forgotten about or overlooked Autodia and other free software that already does this.


    Perl has several GraphViz modules for diagramming databases, classes, etc


    There are also dozens of perl (and other) scripts to generate diagrams from sql, etc in anything from dot to dia.


    ..and of course there is Autodia which has been able to draw class diagrams (in dot, dia and other forms) from python, perl, php, c++, Java, SQL and other sources for quite some time.


    NB I am the author of AutoDia and maintainer of a graphviz module. But if Michele can plug python warez, I'll plug perl stuff ;)

    • Autodia and other software
      2004-05-11 06:22:38  michelesimionato [Reply | View]

      There are *lots* of applications using GraphViz.
      I couldn't list them all, so I just put a link
      to GraphViz home-page (which list AutoDia, BTW).
      Furthermore I said

      "Bindings exist for many programming languages—including Java, Perl, and Python. A more lightweight alternative is just to generate the dot code from your preferred language."

      then I gave an example in Python, essentially
      because it is a readable language even for
      readers that do not know it.

      The message I wanted to pass was that
      for small projects, it maybe faster to
      generate 'dot' code by hand with your preferred
      language than to use an existing tool.
      • fair point apart from class diagrams
        2004-05-11 06:56:50  teejay [Reply | View]

        dot is very fast to generate by small scripts or by hand, and it is a good introduction.


        Python's strongest point is that its a good teaching language (ever tried porting or groking java examples with the dozens of lines creating tiny objects that are used as arguments to a method of another small object to get yet more tiny objects .. uurgh, yes Dr Dobbs I'm talking about you)


        No point reinventing the wheel with class diagrams though.

      • yes, but using a tool is usually quicker
        2004-05-11 06:52:30  teejay [Reply | View]

        ..especially when there is a tool *cough* autodia *cough* that already does it for you, that was in fact designed to solve this problem several years ago.


        perl -MCPAN -e 'install Autodia'

        autodia.pl -d path/to/files -l python -o myclasses.png -Z


        is pretty quick.


        Having said that, yes, dot is very programmable and rapid to code to. Graphviz is very cool, and knocking off a quick script to handle edge-cases is quite satisfying but there is no point re-inventing the wheel.







Tagged Articles

Post to del.icio.us

This article has been tagged:

graphviz

Articles that share the tag graphviz:

An Introduction to GraphViz and dot (3 tags)

View All

visualization

Articles that share the tag visualization:

A Bright, Shiny Service: Sparklines (15 tags)

Styling RDF Graphs with GSS (8 tags)

Big Lists in Small Spaces (3 tags)

Deploying BIRT (3 tags)

Adding Data Visualization to Python for Producing Graphs (3 tags)

View All

dot

Articles that share the tag dot:

An Introduction to GraphViz and dot (2 tags)

View All

Sponsored Resources

  • Inside Lightroom
Advertisement

Sponsored by:

O'Reilly Media

©2009, O'Reilly Media, Inc.
(707) 827-7000 / (800) 998-9938
All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.
About O'Reilly
Academic Solutions
Authors
Contacts
Customer Service
Jobs
Newsletters
O'Reilly Labs
Press Room
Privacy Policy
RSS Feeds
Terms of Service
User Groups
Writing for O'Reilly
Content Archive
Business Technology
Computer Technology
Google
Microsoft
Mobile
Network
Operating System
Digital Photography
Programming
Software
Web
Web Design
More O'Reilly Sites
O'Reilly Radar
Ignite
Tools of Change for Publishing
Digital Media
Inside iPhone
O'Reilly FYI
makezine.com
craftzine.com
hackszine.com
perl.com
xml.com

Partner Sites
InsideRIA
java.net
O'Reilly Insights on Forbes.com