Graphics, Figures & TablesTikZ: alignment of horizontal axis labels

Information and discussion about graphics, figures & tables in LaTeX documents.
Post Reply
johnjamessmith0
Posts: 37
Joined: Sun Mar 29, 2009 1:41 am

TikZ: alignment of horizontal axis labels

Post by johnjamessmith0 »

Consider a horizontal axis with labels at certain points:

Code: Select all

\documentclass{article}

\usepackage{tikz}

\begin{document}


\begin{tikzpicture}
  \draw (0,0) -- (5,0);
  \node [below] at (1,0) {$a$};
  \node [below] at (2,0) {$b$};
  \node [below] at (3,0) {$g$};
\end{tikzpicture}

\bigskip
\bigskip

\begin{tikzpicture}
  \draw (0,0) -- (5,0);
  \node [below] at (1,0) {\vphantom{$abg$}$a$};
  \node [below] at (2,0) {\vphantom{$abg$}$b$};
  \node [below] at (3,0) {\vphantom{$abg$}$g$};
\end{tikzpicture}

\end{document}



The alignment in the first tikzpicture is decidedly suboptimal. But to fix it, the best code I've come up with that of the second tikzpicture above. Is there an easier way?

Thanks.

Recommended reading 2024:

LaTeXguide.org • LaTeX-Cookbook.net • TikZ.org

NEW: TikZ book now 40% off at Amazon.com for a short time.

User avatar
shadgrind
Posts: 140
Joined: Thu Jul 16, 2009 12:39 am

TikZ: alignment of horizontal axis labels

Post by shadgrind »

I don't know if this is easier, but here's my way of doing it:

Code: Select all

\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
  \draw[anchor=base] (0,0) -- (5,0)
   node[shift={(0,-0.4)},pos=0.2] {$a$}
   node[shift={(0,-0.4)},pos=0.4] {$b$}
   node[shift={(0,-0.4)},pos=0.6] {$g$};
\end{tikzpicture}
\end{document}
System: TeX Live 2012, Fedora 18 x86_64, GNU Emacs 24.2
johnjamessmith0
Posts: 37
Joined: Sun Mar 29, 2009 1:41 am

Re: TikZ: alignment of horizontal axis labels

Post by johnjamessmith0 »

That method seems to require some inconvenient precomputation for at least two things: the vertical alignment of the labels and their horizontal alignment. Which means one can't easily remove or add labels that have wacky vertical dimensions, like f_1^2, for example. I hadn't seen that syntax before though, and I'll probably find it useful elsewhere, so thanks.
User avatar
shadgrind
Posts: 140
Joined: Thu Jul 16, 2009 12:39 am

TikZ: alignment of horizontal axis labels

Post by shadgrind »

I prefer using relative positioning, but you could replace that with absolute positioning if you want:

Code: Select all

\begin{tikzpicture}
  \draw[anchor=base] (0,0) -- (5,0)
   node[shift={(0,-0.4)}] at (1,0) {$a$}
   node[shift={(0,-0.4)}] at (2,0) {$b$}
   node[shift={(0,-0.4)}] at (3,0) {$g$};
\end{tikzpicture}
As for the fixed downward vertical shift, you're going to have to do something like that no matter what if you want the labels aligned. The key part is using the anchor=base option. After that, the vertical shift is simple.
System: TeX Live 2012, Fedora 18 x86_64, GNU Emacs 24.2
Post Reply