↓ Skip to main content

Combining graphviz (dot) and TikZ with dot2tex

We all want to cre­ate good look­ing doc­u­ments and good look­ing doc­u­ments need good look­ing im­ages. Be­cause we want con­sist­ency and be­cause we are lazy we want to do this as auto­matic as pos­sible. That is why we use LaTeX, it cre­ates beau­ti­fully type­set doc­u­ments without much manual ef­fort.

Sim­il­arly, we use graphviz to gen­er­ate our graphs for us. It’s auto­matic lay­out is the best in the field and the (de­clar­at­ive) dot lan­guage is easy to un­der­stand and com­pact to write. We can either in­clude the PDFs dot gen­er­ated in our doc­u­ment by us­ing \includegraphics or we could use the latex graphviz pack­age, re­mem­ber that we are lazy. We can eas­ily get the im­age in our first ex­ample in our PDF.

Image with graphviz
Fig­ure 1. Ex­ample of an im­age gen­er­ated by Graphviz/dot

There is a shadow side to us­ing Graphviz/dot as well. There are two prob­lems. Firstly, the im­age just looks a bit out of place around the nicely smoothed text in a PDF. Secondly, we lack the abil­ity to use TeX code in our graph. This means we are lim­ited to the format­ting by dot and the graphs could there­fore ap­pear out of style with other fig­ures in our doc­u­ment.

No wor­ries, with TikZ it is pos­sible to cre­ate very fancy graphs and im­ages in gen­eral but you have to all the po­s­i­tion­ing manu­ally! Ima­gine in­sert­ing a node and hav­ing to re­order everything!

Enter dot2tex it brings all the love of graphviz/dot to TeX/TikZ. Us­ing dot2tex has many ad­vant­ages:

  1. Lets you write your graphs in fa­mil­iar dot syn­tax;
  2. Let dot – or whichever lay­out en­gine you prefer – de­term­ine the place­ment of your nodes and ar­rows;
  3. Style your nodes how­ever you want by us­ing TikZ styles;
  4. Op­tion­ally, fine-tune the graph by adding ex­tra tikz draw­ings.

Rather than manu­ally call­ing dot2tex for every dot file you have please use the dot2texi pack­age. This is the in­ter­face to dot2tex and when used as fol­lows gen­er­ates the im­age as dis­played in Fig­ure 2.

  \begin{tikzpicture}[>=latex',scale=0.5]
    % set node style

    \begin{dot2tex}[dot,tikz,codeonly,styleonly,options=-s -tmath]
        digraph G  {
            node [style="n"];
            p [label="+"];
            t [texlbl="\LaTeX"];
            6
            8
            10-> p;
            6 -> t;
            8 -> t;
            t -> p;
            {rank=same; 10;6;8}
        }
    \end{dot2tex}.
    \begin{pgfonlayer}{background}
        \draw[rounded corners,fill=blue!20] (6.north west) -- (8.north east) -- (t.south east)--cycle;
    \end{pgfonlayer}
\end{tikzpicture}
Example of TeX typesetting + TikZ background
Fig­ure 2. Ex­ample of TeX type­set­ting + TikZ back­ground

For more TikZ good­ness check out the ex­ample site.

Happy writ­ing!