4

I would like to use a macro to define the label of an extra tick in a pgfplots picture. When the macro uses a greek character it generates an error:

! Missing \endcsname inserted.

Here is my MWE:

\documentclass{article}
\usepackage{pgfplots}
\newcommand{\extraticksmwe}{%
    extra y ticks={.5}, extra y tick labels={$\alpha$}%
}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
    ytick={0},
    \extraticksmwe
    ]

\addplot[]{ .5 };
\end{axis}
\end{tikzpicture}
\end{document}

Note that if I do not use a greek character, e.g. using $a$ instead of $\alpha$, the same code above does not generate an error. Similarly, if I do not use a macro at all, it does not generate an error, so the following code works fine:

\documentclass{article}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
    ytick={0},
    extra y ticks={.5}, extra y tick labels={$\alpha$}%
    ]

\addplot[]{ .5 };
\end{axis}
\end{tikzpicture}
\end{document}
Peutch
  • 2,182

1 Answers1

7

You have to expand extraticksmwe first. This can be achieved by

\edef\x{\noexpand\begin{axis}[
    ytick={0},
    \extraticksmwe
    ]
}
\x

However this isn't a nice solution. It also doesn't expand \extraticksmwe only once.

I suggest to use \pgfplotsset inside your new defined command and call it before the environment axis starts:

\newcommand{\extraticksmwe}{%
 \pgfplotsset{%
    extra y ticks={.5}, extra y tick labels={$\alpha$}%
 }
}

Here the complete MWE:

\documentclass{article}
\usepackage{pgfplots}
\newcommand{\extraticksmwe}{%
 \pgfplotsset{%
    extra y ticks={.5}, extra y tick labels={$\alpha$}%
 }
}
\begin{document}
\begin{tikzpicture}
\extraticksmwe
\begin{axis}[ytick={0}]
\addplot[]{ .5 };
\end{axis}
\end{tikzpicture}
\end{document}

If you are willing to avoid a macro you can also define a new style as suggested by percusse.

\pgfplotsset{extraticksmwe/.style={extra y ticks={.5}, extra y tick labels={$\alpha$}}}

This new style can be used inside the optional argument of axis:

\begin{axis}[ytick={0},extraticksmwe]
Marco Daniel
  • 95,681
  • 5
    Using macros inside the options is indeed not a good idea. We can put things into a style extraticksmwe/.style={...} and call that key instead of the macro. – percusse Jun 07 '13 at 10:11