Search code examples
for-looplatextikzpgfplots

For loop is "stucked" inside a pgfplot


I am trying to produce some plots in latex using pgfplots; because of the fact that I have several different plots to produce, I am trying to use a for loop. Unfortunately, without success. Indeed, the code is executed three times but the value of the variable of the for loop it is always equal to the first value of the list that defines the loop.

For example, the following minimal code

\documentclass[a4paper, 11pt]{article}

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

\begin{document}

\makeatletter
\begin{tikzpicture}
  \begin{groupplot}[group style={group size= 2 by 3}]
    \@for\refin:={1,2,3}\do{%
      \nextgroupplot[ylabel={$h = \frac{1}{\refin}$}]
        \addplot {exp(x)};
      \nextgroupplot
        \addplot{2  * x};
    }
  \end{groupplot}
\end{tikzpicture}
\makeatother

\end{document}

Produces a figure with 6 plots (as expected) but the label is always 1/1 and never 1/2 or 1/3. Why?


Solution

  • You can use the same trick as https://tex.stackexchange.com/a/539754/36296 :

    \documentclass[a4paper, 11pt]{article}
    
    \usepackage{pgffor}
    \usepackage{pgfplots}
    \pgfplotsset{compat=1.13}
    \usepgfplotslibrary{groupplots}
    
    \begin{document}
    
    \begin{tikzpicture}
      \begin{groupplot}[group style={group size= 2 by 3}]
        \pgfplotsforeachungrouped \x in {1,2,3}{
        \edef\tmp{
            \noexpand\nextgroupplot[ylabel={$h = \frac{1}{\x}$}]
            \noexpand\addplot {exp(x)};     
        }
        \tmp          
          \nextgroupplot
            \addplot{2  * x};
        }
      \end{groupplot}
    \end{tikzpicture}
    
    
    \end{document}
    

    enter image description here