# pgfplots - x unit with siunitx

I want to use x unit=something to draw the units to an axis. In the manual I find this to use siunitx to do so:

\pgfplotsset{
unit code/.code 2 args={\si{#1#2}}
}


Now I make a plot:

\begin{axis}[
xlabel = $$E$$,
x unit={\mega\electronvolt.m}
]


The dot is written, which should not be. Manually, this works:

\begin{axis}[
xlabel = $$E$$,
x unit=\si{\mega\electronvolt.m}
]


What am I doing wrong?

-
You're mixing the literal (MeV.m) and "interpreted" (\mega\electronvolt\m) input modes of siunitx, which for some reason doesn't work in the x unit code. If you stick with the interpreted mode, so say x unit={\mega\electronvolt\m}, the output is correct. Also note that you should probably be using \pgfplotsset{unit code/.code={\si{\@secondoftwo#1}}} as Joseph Wright explains at tex.stackexchange.com/questions/12135/…. – Jake Feb 6 '13 at 9:39
Ok, indeed it works with the interpreted input mode. Only using (and not mixing as I did) literal does't work either. So my question reduces to a question of convenience! I just like to use the literal, if that is not possible, so it is. – DaPhil Feb 6 '13 at 9:57
We'll have to wait for Joseph Wright to find this question, he might have a way of using literal input in this context. I would recommend using interpreted input anyway, though, because only that opens up all the nice features siunitx offers. If you don't use it, you might as well just type MeV\,m without using siunitx at all and get the same output. – Jake Feb 6 '13 at 10:00
NO! You should rather enjoy lunch :) – DaPhil Feb 6 '13 at 10:03

The issue is that pgfplots passes the unit 'wrapped up' inside some code. To get it out correctly here we have to take steps to expand it.

\documentclass{standalone}
\usepackage{pgfplots,siunitx}
\usepgfplotslibrary{units}
\makeatletter
\pgfplotsset{
unit code/.code 2 args=
\begingroup
\protected@edef\x{\endgroup\si{#2}}\x
}
\makeatother
\begin{document}
\begin{tikzpicture}

\begin{axis}[
xlabel = $$E$$,
x unit=\mega\electronvolt.m]
\end{axis}

\end{tikzpicture}
\end{document}


You can do the same with \expandafter but you need a lot of them!

\documentclass{standalone}
\usepackage{pgfplots,siunitx}
\usepgfplotslibrary{units}
\pgfplotsset{
unit code/.code 2 args=
\expandafter\expandafter\expandafter\expandafter
\expandafter\expandafter\expandafter\si
\expandafter\expandafter\expandafter\expandafter
\expandafter\expandafter\expandafter{#2}%
}

\begin{document}
\begin{tikzpicture}

\begin{axis}[
xlabel = $$E$$,
x unit=\mega\electronvolt.m]

The reason you have to force expansion is that unlike numbers, siunitx does not try to expand units: it expects them to be given 'as is'. As such, the search-and-replace for . fails as it's 'hidden' inside a pgfplots macro.