[Tex/LaTex] Using LaTeX commands inside pgfplotsset

pgfkeyspgfplots

Is there any way to use LaTeX commands inside \pgfplotsset?

For instance, the following code produces an error indicated in the \pgfplotsset line, whereas if one replaced \contents in the \pgfplotsset command with axis x line=bottom then all would be well.

\documentclass{article}


\usepackage{pgfplots}
\newcommand{\contents}{axis x line=bottom}

\begin{document}
\begin{tikzpicture}

\pgfplotsset{\contents}  % <----- fails with ! Package pgfkeys Error: I do not know the key '/pgfplots/axis x line=bottom'

\begin{axis}
\addplot[domain=-3e-3:3e-3,samples=201]{exp(-x^2 / (2e-3^2)) / (1e-3 * sqrt(2*pi))};
\end{axis}
\end{tikzpicture}

\end{document}

Best Answer

Probably Till Tantau was having similar problems so he created the error messages in a smarter way. Example; if I go something like this

\tikz[xasfwr=yeah]{}

The error message is

Package pgfkeys Error: I do not know the key /tikz/xasfwr, to which you passed yeah, and I am going to ignore it. Perhaps you misspelled it.

Now your example; let's read the error message

Package pgfkeys Error: I do not know the key /pgfplots/axis x line=bottom

Notice that it doesn't say you tried to pass bottom it says that it didn't understand the whole thing. Because it didn't parse it and missed the equation sign and the value you have provided. You can get more stupid cases such as

\pgfplotsset{\contents=out haha so funny}

Package pgfkeys Error: I do not know the key /pgfplots/axis x line=bottom, to which you passed out haha so funny, and I am going to ignore it.

These all tell that PGF keys didn't expand it properly. One immediate thing is to manually expand the argument by delaying the expandion of \pgfplotsset{ part

\expandafter\pgfplotsset\expandafter{\contents}

would work. Or you can still stay within PGF keys and use the /.expanded handler which does the expansion for you.

\pgfkeys{/utils/exec/.expanded={\noexpand\pgfplotsset{\contents}}}

What does this do? First, /utils/exec is the general handler for executing arbitrary TeX code. Then by just identifying what should not be expanded, here \pgfplotsset and adding \noexpand before them, you can set any kind of macro values.

You can also control how many times it should expand and you can check the manual for expand once and expand twice keys for that.