Drawing Finite Automata and State Machines

I had to draw a couple of Finite Automata and Turing Machines for some university assignments. Usually, I would have done it using Inkscape (as it is my favorite tool for creating figures for my LaTeX documents), but doing it manually is pretty tedious work. Inkscape’s diagram tool is currently subpar, so everything has to be done by hand. It’s OK if you need to draw one State Machine once in a while, but it’s not suitable for larger quantities. I’ve also tried using Dia, but it also required lots of manual tweaking and tuning.

To my surprise, Graphviz (and especially the dot utility) turned out to be the (almost) perfect tool for the job. It lets you describe the graph in a simple text-based way, and it handles the graph layout by itself. This is somewhat like LaTeX, but for graphs (you concentrate on content, not layout).

My Finite Automata needed no manual tweaking and resulted in very nice graphs. For more complicated State Machines, it’s sometimes necessary to do some manual tuning. The commands I found most useful to tweak the graph were:

  • Grouping nodes to be on the same level – { rank="same"; "q1"; "q2"; "q3"}. The other options for rank can affect how the group is positioned relative to the other nodes in the graph (source, above all, sink below all).
  • Adding weight to edges – q1 -> q2 [weight="10"]. This affects the cost of stretching the edge. The higher the weight, the straighter the edges will be.
  • Adding invisible edges – q1 -> q3 [style="invis"]. This allowed me to control the order of the nodes in the same rank (height).

Last but not least, Graphviz can generate graphs in a variety of formats, including eps, pdf, and svg (which allows post-processing with Inkscape).