1

I am generating a set of figures inside a foreach loop. I would like to save each figure as an individual image (with any extension). How could I achieve this? Below is the code I use to generate the figures:

\documentclass[11pt]{article}
\usepackage{float}
\usepackage{tikz}
\begin{document} 

\foreach \x/\y in {3.8/4,5.7/5,6.4/5 }
{   
    \begin{figure}[H]
        \centering
        \begin{tikzpicture}
            \draw[draw=black, very thick, fill=gray!30] (0,0) rectangle ++(\x,\y);
        \end{tikzpicture}
        \caption{Base \x~cm and height \y~cm.}
    \end{figure}
}

\end{document}

In reality I am generating over 200 complex figures inside the loop. Can anyone point me into the right direction?

1
  • Maybe using the standalone document class. The PDF can be split using a PDF software. Dec 23 '20 at 3:37
3

By using tikz's external library all your images created inside tikzpicture will automatically be saved externally as separate files upon creation (in the case below, in /tikzpics in your working folder). This has the main advantage that subsequent compilations don't recreate each image, instead they are searched for in the save folder and loaded, unless they were modified in your source code.

\documentclass[11pt]{article}
\usepackage{float}
\usepackage{tikz}
\usetikzlibrary{external}

\tikzexternalize
\tikzsetexternalprefix{tikzpics/}

\begin{document} 

\foreach \x/\y in {3.8/4,5.7/5,6.4/5 }
{   
    \begin{figure}[H]
        \centering
        \begin{tikzpicture}
            \draw[draw=black, very thick, fill=gray!30] (0,0) rectangle ++(\x,\y);
        \end{tikzpicture}
        \caption{Base \x~cm and height \y~cm.}
    \end{figure}
};

\end{document}

In this way, all the images you create will be found in the specified folder as separate pdf files.

You can take a look at section 52 of pgfmanual for more details on how it works. Beware that for the externalization to work, you have to enable system calls (you can refer to the manual for it).

1
  • I would only add that you can have \tikzsetnextfilename{\x_\y} before every picture to give it a custom name based on the loop variables. Dec 23 '20 at 16:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.