Drawing graphs with graphviz

If you’ve read any of my posts regarding regular expressions you’ve seen these little graphs. I just wanted to tell you all how they were made. They might not be very pretty, but it’s easy to produce them, especially programmatically from source code. In fact, it’s so easy that I’ve included graph output as a standard debugging feature in my parser generator. And they can get quite pretty indeed, if you know what you’re supposed to do.

This is part of a library called GraphViz. Unfortunately the graphviz tool set is about as user friendly as a bicycle without a saddle attached. Well, they do have a GvEdit application that you can input stuff in and get a graph. I suggest using this online tool and just right-click to save your graphs. That’s what I do anyway.

I find it remarkable what you can achieve with this tool, and I use it more and more since I loathe to draw and layout things by hand. A basic directed graph looks like this:

digraph g {
  a -> b
  b -> c
  c -> a

If you want more nodes, just add them in and draw arrows. Easy. The engine will lay this out for you and present you with a pretty picture. I’m by no means an expert, but I have gathered a few tricks (use inside of the brackets unless stated otherwise).

  • Graphviz likes to draw with arrows pointing downwards. Use graph [rankdir="LR"] to make it tend to draw left to right instead
  • Change the default node shape by adding node [shape="whatever shape you want"]. Theres a few to choose from, in my graphs i used circle and doublecircle
  • Add lables to your little arrows by adding [label=”xx”] after the end node.
  • Whichever node you define first will tend to be drawn to the upper left

This is the tip of the iceberg really, graphviz.org has lots more information. As long as you don’t try to position the nodes manually you’re pretty much good to go. It really is a tool for getting graphs without having to do all the cumbersome work with moving stuff around to make it pretty. If you need fine grained per-pixel control, this isn’t for you. If you need to get a graph up and running quickly and to modify it easily, this tool should be right up your alley.

Tagged , ,

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

%d bloggers like this: