# Changing parameters in a groupplot

The idea behind the following sample code is this: There should be four plots, and for each plot two parameters should be set. This is achieved through \def just before \nextgroupplot. Apparently, this approach is not sound.

\documentclass{beamer}

\usepackage{pgfplots}
\pgfplotsset{compat=1.7}
\usepgfplotslibrary{groupplots}

\begin{document}

\begin{frame}
\begin{tikzpicture}
\begin{groupplot}[group style={group size=2 by 2}, height=5cm, width=6cm]
\def\myA{1}
\def\myB{1}
\nextgroupplot[xlabel = {A: \myA, B: \myB} ]

\def\myA{1}
\def\myB{2}
\nextgroupplot[xlabel = {A: \myA, B: \myB} ]

\def\myA{2}
\def\myB{1}
\nextgroupplot[xlabel = {A: \myA, B: \myB} ]

\def\myA{2}
\def\myB{2}
\nextgroupplot[xlabel = {A: \myA, B: \myB} ]
\end{groupplot}
\end{tikzpicture}
\end{frame}
\end{document}


Here's the output of the above snippet: .

If everything worked as planned, we would see four different figures, with different values at x=1 and x=2, labelled like this:

A: 1, B:1   A: 1, B:2
A: 2, B:1   A: 2, B:2


Neither works. All four plots appear to take their parameters from the very first definition only. For the labels, the order is changed (2-3-4-1 rather than 1-2-3-4).

Q: Why is that? What's the proper way to do what I mean to do?

Q: Why can't I write that code as

\documentclass{beamer}

\usepackage{pgfplots}
\pgfplotsset{compat=1.7}
\usepgfplotslibrary{groupplots}

\begin{document}

\def\myAs{1,2}
\def\myBs{1,2}

\begin{frame}
\begin{tikzpicture}
\begin{groupplot}[group style={group size=2 by 2}, height=5cm, width=6cm]
\foreach\myA in \myAs{
\foreach\myB in \myBs{
\nextgroupplot[xlabel = {A: \myA, B: \myB} ]
}
}
\end{groupplot}
\end{tikzpicture}
\end{frame}
\end{document}

• pgfplots doesn’t execute everything right away but collects the plots calculates stuff and then draws it. See also section 8.1 “Utility commands”, pp. 417ff., of the manual for this. Aug 31, 2013 at 1:29

The pgfplots package doesn’t execute everything right away but does collect the plots first, calculated stuff and then actually draws something. With the etoolbox package you can use your two loops (at least in this example) pretty easily to build a macro that contains all Plots with expanded values \myA and \myB.

## Code

\documentclass{beamer}

\usepackage{pgfplots,etoolbox}
\pgfplotsset{compat=1.7}
\usepgfplotslibrary{groupplots}

\begin{document}

\def\myAs{1,2}
\def\myBs{1,2}

\begin{frame}
\begin{tikzpicture}
\begin{groupplot}[group style={group size=2 by 2}, height=5cm, width=6cm]
\def\myPlots{}
\pgfplotsforeachungrouped \myA in {1,2}{
\pgfplotsforeachungrouped \myB in {1,2}{
\eappto\myPlots{%
\noexpand\nextgroupplot[xlabel = {A: \myA, B: \myB} ]