TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Is it possible to automatically change the position of every other x tick label in pgfplots?

This is my scenario: I have a plot with symbolic x tick labels loaded from the table. Those labels are too wide to fit next to each other:

enter image description here

What I would like to have is that every other label is automatically shifted a bit downwards like in this example:

enter image description here

Minimal working code for the "bad" example:

\documentclass[a4paper]{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.5}

\begin{filecontents}{data.txt}
  label     x y
  foobarbaz 0 1
  foobarbaz 1 1
  foobarbaz 2 1
  foobarbaz 3 1
  foobarbaz 4 1
\end{filecontents}

\begin{document}
\begin{tikzpicture}
  \begin{axis}[
      ybar,
      x=1cm,
      xtick=data,
      xticklabels from table={data.txt}{label},
    ]
    \addplot table [x=x, y=y] {data.txt};
  \end{axis}
\end{tikzpicture}
\end{document}

For the "good" one I manually added \raisebox to every other label:

\begin{filecontents}{data.txt}
  label     x y
  foobarbaz 0 1
  \raisebox{-4ex}{foobarbaz} 1 1
  foobarbaz 2 1
  \raisebox{-4ex}{foobarbaz} 3 1
  foobarbaz 4 1
\end{filecontents}

However, since my actual data contains much more lines, I don't want to do it manually like this. Is there a way to do this automatically with pgfplots?

share|improve this question
up vote 4 down vote accepted

You could use

x tick label style={yshift={-mod(\ticknum,2)*1em}}

enter image description here

Code:

\documentclass[a4paper]{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.5}

\begin{filecontents}{data.txt}
  label     x y
  foobarbaz 0 1
  foobarbaz 1 1
  foobarbaz 2 1
  foobarbaz 3 1
  foobarbaz 4 1
\end{filecontents}

\begin{document}
\begin{tikzpicture}
  \begin{axis}[
      ybar,
      x=1cm,
      xtick=data,
      xticklabels from table={data.txt}{label},
      x tick label style={yshift={-mod(\ticknum,2)*1em}}
    ]
    \addplot table [x=x, y=y] {data.txt};
  \end{axis}
\end{tikzpicture}
\end{document}
share|improve this answer
    
Nice method! Would you mind also adding an answer to tex.stackexchange.com/questions/164673/…? – Jake Feb 29 at 11:57

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.