# Plot multiple files using pgfplots

Often, I like to plot multiple versions of some results. For example, I run some simulations for multiple parameters, or test a bunch of different methods. Although it is of course no problem to create different plots for the different results automatically, using for example matplotlib, I usually resort to pgfplots for the final figures. It produces very high quality plots that you can control very well, especially because it uses TikZ in the background. But automating it can sometimes be a bit difficult.

Here’s what I did for creating several plots in groupplots. The problem is that a normal \foreach doesn’t work for the plotting, but unfortunately, neither do the pgfplots alternatives \pgfplotsforeachungrouped and \pgfplotsinvokeforeach in the case of nested loops. It seems there are some difficulties with expansion and evaluation of the sorts. Fortunately, I came across this answer of stackexchange. By using the etoolbox we can use the command \eappto to append some code to a command. We just need to make sure we don’t expand the commands too soon by using a \noexpand. All in all, here’s what we get.

    \def\myPlots{}
\pgfplotsforeachungrouped \x in {1,2,3}
{
\pgfplotsforeachungrouped \y in {1,2,3}
{
\eappto\myPlots{%
\noexpand\nextgroupplot

You have to put this in a groupplots environment of course, and make sure your preamble is all correct. But then this makes quite a nice way to automate the plots using multiple files.