Using Relative Units in TikZ Drawings

I used to happily create TikZ drawings with pt units, let’s say in a paper using the IEEE style:

\documentclass{IEEEtran}
\usepackage{tikz}
\usetikzlibrary{positioning}
 
\begin{document}
\begin{tikzpicture}
\node[text width=60pt] (mor){Morphological Analysis};
\node[text width=35pt,right=12pt of mor] (syn) {Syntactic Analysis};
\draw[-latex] (mor) -- (syn);
\end{tikzpicture}
\end{document}

The output looks good enough, although I did have to try several times getting the text widths right:

But often times I’d want to reuse my TikZ code in other documents, e.g. a Beamer presentation, or my thesis in which I must use Times 11pt. But when I happily copied over my Tikz snippet over, I get:

\documentclass{beamer}
...
\begin{tikzpicture}
...
\end{tikzpicture}
...
\documentclass[11pt]{memoir}
\usepackage{mathptmx}
...
\begin{tikzpicture}
...
\end{tikzpicture}
...

Ouch, it looks like I need to figure out the different text width values in pts by trial and error, for each document I want to include my picture in!

Or do I?

The real issue here is that pt is an absolute unit (1pt = 1/72 inch), so my TikZ node’s text width stays the same while the font metrics is different in each document. Using relative units, like em or ex, would make my life a lot easier.

Let me explain: 1em is the height of the current typeface in the current size, and is a little bit wider than a capital ‘M’. This means the length/width 1em depends on the active font family and size.

And as a rough estimate, a capital ‘M’ is twice as long as a lowercase letter. ‘Morphological’ has 1 ‘M’ and 12 lower case letters, but 3 of these are ‘thin’ letters (‘l’ and ‘i’), so I’d go with 6em rather then 7. Similarly, I’d try 4em for ‘Syntactic Analysis’.

Let’s see the results, using the same TikZ code in all three versions (IEEE paper, beamer and typical thesis):

\documentclass{IEEEtran}
\usepackage{tikz}
\usetikzlibrary{positioning}
 
\begin{document}
\begin{tikzpicture}
\tikzset{every node/.style={draw,align=center}}
\node[text width=6em] (mor){Morphological Analysis};
\node[text width=4em,right=1em of mor] (syn) {Syntactic Analysis};
\draw[-latex] (mor) -- (syn);
\end{tikzpicture}
\end{frame}
\end{document}
\documentclass{beamer}
...
\begin{tikzpicture}
...
\end{tikzpicture}
...
\documentclass[11pt]{memoir}
\usepackage{mathptmx}
...
\begin{tikzpicture}
...
\end{tikzpicture}
...

There! The text widths would vary relative to the current font families and sizes in use, so I won’t have to fiddle around with pt values for every new document I want to incorporate my existing TikZ code.

One thought on “Using Relative Units in TikZ Drawings

Leave a Reply

Your email address will not be published. Required fields are marked *