Tx · LaTeX & TikZ

How to Insert Multiple Figures with a Python Loop in LaTeX

Published By the 9to5Science editorial team

At a glance

  1. 1. Load the packages

    Load graphicx to include images and pythontex to execute Python code from the document.

  2. 2. Loop over filenames

    Use a Python loop to print one includegraphics command for each figure.

  3. 3. Run PythonTeX

    Compile LaTeX, run PythonTeX on the source file, then compile LaTeX again.

  4. 4. Check paths

    Make sure every image path is correct relative to the directory where you compile.

PythonTeX lets you execute Python code while building a LaTeX document. To insert several images, loop through their filenames and have Python print LaTeX commands such as \includegraphics. The example below creates a separate figure environment for each image.

Minimal example

Put the following in main.tex. It assumes that the image files plot_1.pdf, plot_2.pdf, and plot_3.pdf are in a folder named figures beside the TeX file.

\documentclass{article}
\usepackage{graphicx}
\usepackage{pythontex}

\begin{document}

\begin{pyblock}
for n in range(1, 4):
    print(r"\begin{figure}[htbp]")
    print(r"\centering")
    print(r"\includegraphics[width=0.7\linewidth]{figures/plot_%d.pdf}" % n)
    print(r"\caption{Plot %d}" % n)
    print(r"\end{figure}")
\end{pyblock}

\end{document}

The graphicx package provides \includegraphics, and pythontex defines the pyblock environment. In the loop, range(1, 4) produces the integers 1, 2, and 3. Each iteration prints LaTeX for one figure. The raw Python strings (the r before the opening quote) make backslashes in LaTeX commands easier to write.

Compile the document on Windows

Run the commands from the folder containing main.tex, so the relative image paths resolve correctly. The usual sequence is:

  1. Run your LaTeX engine on main.tex, for example pdflatex main.tex.
  2. Run the PythonTeX script on the same source file, commonly pythontex main.tex.
  3. Run the LaTeX engine again, for example pdflatex main.tex.

The first LaTeX run creates files PythonTeX needs. PythonTeX then executes the code and writes its output for LaTeX to use; the final LaTeX run incorporates that output into the PDF. Depending on how MiKTeX or another TeX distribution is installed, the PythonTeX command may have a different launcher name. Use the command installed with your distribution, and ensure Python is available to it.

Change the list or layout

For files that do not follow a numbering pattern, loop over an explicit list instead:

files = ["overview.pdf", "detail.pdf", "results.pdf"]
for filename in files:
    print(r"\includegraphics[width=0.7\linewidth]{figures/%s}" % filename)

You can put this code in a pyblock and add figure environments, captions, or spacing around the printed command. If each image should be inline rather than a floating figure, print only the \includegraphics command and omit the figure environment.

Common mistakes

  • Skipping the PythonTeX run: LaTeX alone does not execute the Python loop. Run PythonTeX between LaTeX runs.
  • Using the wrong working directory: Paths such as figures/plot_1.pdf are interpreted relative to the directory used for compilation, not necessarily the location of the image in File Explorer.
  • Mismatched filenames or extensions: Check spelling, capitalization, and whether the files are actually PDF, PNG, or another supported format.
  • Using pycode when you need printed LaTeX: pycode is for executing Python without inserting its printed output as document content. Use pyblock for this generated LaTeX pattern.
  • Expecting a loop to fix a missing image: The generated \includegraphics commands still need valid files. Test one image path directly in LaTeX before generating many commands.

When a Python loop is unnecessary

If your filenames are regular and you do not need Python calculations, a LaTeX loop can be simpler and avoids an extra PythonTeX processing step. For example, the pgffor package provides \foreach. PythonTeX is useful when the list comes from Python data, filenames are computed, or the figure set changes as part of a Python workflow.

References

  1. PythonTeX: LaTeX Documents with Python Code
  2. LaTeX2e unofficial reference manual: \includegraphics

Spotted an error? Send a correction. Read how we write and check articles in our editorial policy.