Thursday, June 12, 2008

Scripting Diagrams

Oftentimes, one of the hardest things to do when constructing a visual representation is getting the layout of the diagram right. However, many visualisation tools incorporate layout engines that take care of all that hard work for you - just provide a textual description (albeit in a structured way) and the visulisation tool will generate the diagram (sometimes even an interactive diagram) for you.

For example, Graphviz is an open source graph visulisation toolkit that construct visual representations of mathematical graphs from a textual description of the graph. (You can see a wide range of examples of the sorts of thing that Graphviz can do in the Graphviz gallery).

Let's have a quick look at how we can create a couple of graphs in Graphviz.

Firstly, consider this tree diagram.



How long do you think it would take you to draw and layout a diagram similar to that? How much effort would be involved if you wanted to change the labels, or add another node or two to the hierarchy?

Using Graphviz, it took me maybe 5 minutes to "script" the tree, and then just a few seconds for Graphviz to display it for me (I actually used a Mac based interface to Graphviz from which I captured the diagram).

Here's how I described the tree to Graphviz:

digraph G {
  a -> b;
  a -> c;
  b -> d;
  b -> e;
  c -> f;
  c -> g;
  c -> h;
  g -> i;
  g -> j;
}


How about a more complicated diagram?


digraph G {
  a -> b;
  a -> c;
  b -> d;
  b -> e;
  c -> f;
  e -> f;
  c -> g;
  c -> h;
  g -> i;
  g -> j;
  f -> i;
  e -> g;
}


Or maybe even one like this?


digraph G {
  a -> b;
  a -> c;
  b -> d;
  b -> e;
  c -> f;
  e -> f;
  c -> g;
  c -> h;
  d -> g
  e -> inevitable1;
  f -> inevitable1;
  g -> inevitable1;
  h -> inevitable1;
  inevitable1 -> i;
  inevitable1 -> j;
  inevitable1 -> k;
  i -> l;
  j -> m;
  j -> n;
  k -> n;
  l-> o;
  k-> o;
  j-> p;
  l -> q;
  n -> r;
  p -> s;
  m -> t;
  s -> t;
  s -> o;
  o -> r;
  q -> inevitable2;
  r -> inevitable2;
  s -> inevitable2;
  t -> inevitable2;
}


Try to create some of your own graphs using Graphviz. As well as the 'simple' views I have shown above, you can also script far more complex diagrams, include the use of colour, and so on. One of the best ways of learning how to enrich your own diagrams is to look through the Graphviz gallery, find a graph that displays a feature or effect that you would like to use, click through to the gallery page for that graph and then click on the graph image to 'view source' of the script that was used to generate the graph. Inspection of it should reveal how to create the required effect.

No comments: