Subfigure example

This example shows subfigure functionality.

The code

import os

from pylatex import Document, Figure, NoEscape, Section, SubFigure

if __name__ == "__main__":
    doc = Document(default_filepath="subfigures")
    image_filename = os.path.join(os.path.dirname(__file__), "kitten.jpg")

    with doc.create(Section("Showing subfigures")):
        with doc.create(Figure(position="h!")) as kittens:
            with doc.create(
                SubFigure(position="b", width=NoEscape(r"0.45\linewidth"))
            ) as left_kitten:
                left_kitten.add_image(image_filename, width=NoEscape(r"\linewidth"))
                left_kitten.add_caption("Kitten on the left")
            with doc.create(
                SubFigure(position="b", width=NoEscape(r"0.45\linewidth"))
            ) as right_kitten:
                right_kitten.add_image(image_filename, width=NoEscape(r"\linewidth"))
                right_kitten.add_caption("Kitten on the right")
            kittens.add_caption("Two kittens")

    doc.generate_pdf(clean_tex=False)

The generated files

subfigures.tex
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
\documentclass{article}%
\usepackage[T1]{fontenc}%
\usepackage[utf8]{inputenc}%
\usepackage{lmodern}%
\usepackage{textcomp}%
\usepackage{lastpage}%
\usepackage{subcaption}%
\usepackage{graphicx}%
%
%
%
\begin{document}%
\normalsize%
\section{Showing subfigures}%
\label{sec:Showingsubfigures}%


\begin{figure}[h!]%
\begin{subfigure}[b]{0.45\linewidth}%
\includegraphics[width=\linewidth]{/home/jelte/fun/pylatex/docs/source/_static/examples/../../../../examples/kitten.jpg}%
\caption{Kitten on the left}%
\end{subfigure}%
\begin{subfigure}[b]{0.45\linewidth}%
\includegraphics[width=\linewidth]{/home/jelte/fun/pylatex/docs/source/_static/examples/../../../../examples/kitten.jpg}%
\caption{Kitten on the right}%
\end{subfigure}%
\caption{Two kittens}%
\end{figure}

%
\end{document}

subfigures.pdf

../_images/subfigures.pdf.png