# Create macro from fairly complex pgfplots code

I have this pgfplots code that takes data from a file mydata.tsv and creates a bar plot. Now I would like to transform it into a macro in order to use it for several files.

\pgfplotstableread[col sep=tab]{mydata.tsv}\datatable
\makeatletter
\pgfplotsset{
/pgfplots/flexible xticklabels from table/.code n args={3}{
\pgfplotstablegetcolumn{#2}\of{\coordinate@table}\to\pgfplots@xticklabels
\let\pgfplots@xticklabel=\pgfplots@user@ticklabel@list@x
}
}
\makeatother

\begin{tikzpicture}
\begin{axis}[
ybar,
ymin=0,
ylabel=\si{\micro\second},
flexible xticklabels from table={mydata.tsv}{stage}{col sep=tab},
xticklabel style={rotate=90, anchor=east},
xtick=data]
plot [error bars/.cd, y dir=both, y explicit]
table[x expr=\coordindex, y=mean, y error=error]{\datatable};
\end{axis}
\end{tikzpicture}


After looking at some introduction to macros, I tried this:

\newcommand{\myplot}[1]{
% same code as above, with "mydata.tsv" replaced by "#1"
}
\myplot{mydata1.tsv}
\myplot{mydata2.tsv}


But I got the following error:

Package pgfplots Error: Sorry, could not retrieve column 'stage' from table '{stage}{mean}{error}@table'.


I am assuming that there is some problem with the existing #1,#2,#3 in my code, I also tried replacing those by ##1,##2,##3, but that didn't help (same error).

EDIT: this is what the data from mydata.tsv looks like:

stage   mean        error
One     27.19143    0.274788478838
Two     27.83391    0.354268822434
Three   87.15405    0.437466618964


(separated by tabs, probably not rendered correctly by stackexchange)

• Done. Btw, in case that was not clear, plotting works perfectly fine for my example, the error only appears when I try to turn it into a macro. – ValarDohaeris Feb 19 '14 at 0:29

I've used comma instead of tab but you can change it back. You don't need to create the keys inside the definition. Also your definition of parameters should match the tabbed version. #2 becomes stage<tab> in your system probably.

\documentclass{article}
\usepackage{pgfplotstable,filecontents,siunitx}
\pgfplotsset{compat=1.9}

\begin{filecontents*}{mydata1.tsv}
stage,mean,error
One,27.19143,0.274788478838
Two,27.83391,0.354268822434
Three,87.15405,0.437466618964
\end{filecontents*}

\makeatletter
\pgfplotsset{%
/pgfplots/flexible xticklabels from table/.code n args={3}{
\pgfplotstablegetcolumn{#2}\of{\coordinate@table}\to\pgfplots@xticklabels
\let\pgfplots@xticklabel=\pgfplots@user@ticklabel@list@x
}
}%
\makeatother

\newcommand{\myplot}[1]{%
%
\begin{tikzpicture}
\begin{axis}[
ybar,
ymin=0,
ylabel=\si{\micro\second},
flexible xticklabels from table={#1}{stage}{col sep=comma},
xticklabel style={rotate=90, anchor=east},
xtick=data]
plot [error bars/.cd, y dir=both, y explicit]
table[x expr=\coordindex, y=mean, y error=error]{\datatable};
\end{axis}
\end{tikzpicture}%
}

\begin{document}
\myplot{mydata1.tsv}
\end{document}