3

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?

1 Answer 1

11

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}
1

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .