# macro within pgfplots in beamer

I want to create a macro so that in a beamer presentation it produces the same plot with slightly different data. But it seems as though a problem exists before I include an argument in the macro. Below is a MWE that demonstrates the problem.

The first frame includes the plot and it works, whereas the second has the same plot as a macro, it doesn't show the plotted points.

\documentclass{beamer}
\usepackage{pgfplots}

\begin{document}

\newcommand{\showplot}{%
\begin{tikzpicture}
\begin{axis}
xval yval
1  7
2  8
};
\end{axis}
\end{tikzpicture}
}

\begin{frame}[fragile]{Example works}

\begin{tikzpicture}
\begin{axis}
xval yval
1  7
2  8
};
\end{axis}
\end{tikzpicture}

\end{frame}

\begin{frame}[fragile]{Example doesn't work}

\showplot

\end{frame}

\end{document}


It seems to be a problem with having the data inside the \addplot It can be fixed by moving it into a filecontents file. I don't know the reason for this being a problem, so I cannot make an answer that works in a different way, although it might very well be possible:

\documentclass{beamer}
\usepackage{pgfplots}
\usepackage{filecontents}
\begin{filecontents}{table.txt}
xval yval
1  7
2  8
\end{filecontents}

\newcommand{\showplot}{%
\begin{tikzpicture}
\begin{axis}
xval yval
1  7
2  8
};
\end{axis}
\end{tikzpicture}
}

\newcommand{\showplotthatworks}{%
\begin{tikzpicture}
\begin{axis}
\end{axis}
\end{tikzpicture}
}

\begin{document}

\begin{frame}[fragile]{Example works}

\begin{tikzpicture}
\begin{axis}
xval yval
1  7
2  8
};
\end{axis}
\end{tikzpicture}

\end{frame}

\begin{frame}[fragile]{Example works using command}
\showplotthatworks
\end{frame}

\begin{frame}[fragile]{Example doesn't work}
\showplot
\end{frame}

\end{document}


produces

• Many thanks. This indeed works. It also works when I extract the table as an argument for the macro. – Geoff May 18 at 11:12
• @Geoff No problem ;-) and good to know – Thorbjørn E. K. Christensen May 18 at 11:19

Out of curiosity, I tried using a savebox instead of a macro. Initial results were not successful, but was able to overcome the problem by adding explicit row separators. Will work on macros as well.

\documentclass{beamer}
\usepackage{pgfplots}

\newsavebox{\showplot}

\savebox{\showplot}{%
\begin{tikzpicture}
\begin{axis}
xval yval\\
1    7\\
2    8\\
};
\end{axis}
\end{tikzpicture}%
}
\begin{document}

\begin{frame}[fragile]{Example works}
\begin{tikzpicture}
\begin{axis}
xval yval
1  7
2  8
};
\end{axis}
\end{tikzpicture}
\end{frame}

\begin{frame}{Example is not fragile.}
\usebox\showplot
\end{frame}

\end{document}