Skip to main content
Back to guides
6 min read

How to Add Figures & Subfigures in LaTeX (graphicx)

Master image insertion, relative scaling, float positioning, and side-by-side subfigures in LaTeX using graphicx and subcaption. Full code examples.

By Dr. Julian Thorne

Visual figures, diagnostic plots, and system architecture schematics are central to scientific and technical publishing. Yet for newcomers and experienced authors alike, managing images in LaTeX frequently causes confusion. Figures jump across page boundaries, subfigures refuse to sit side-by-side, and cross-references print section numbers instead of figure numbers.

In this comprehensive guide, we demystify image inclusion in modern LaTeX using the industry-standard graphicx and subcaption packages. You will learn how to configure image directories, control relative dimensions, tame LaTeX’s floating algorithm, and structure publication-grade side-by-side subfigures.


1. The Core Setup: graphicx & Supported Formats

In modern LaTeX (pdfLaTeX, LuaLaTeX, XeLaTeX), image loading is handled by the graphicx package. Always import it in your document preamble:

\usepackage{graphicx}

Organizing Image Files with \graphicspath

Rather than typing relative paths like \includegraphics{figures/results/benchmark.png} repeatedly, define a central image directory using \graphicspath:

% Tell LaTeX where to search for graphic files:
\graphicspath{{figures/}{images/}}

Syntax Tip: Notice the double curly braces {{figures/}}. Each path must be enclosed in its own set of braces and must terminate with a trailing slash /.

Best File Formats for Scholarly Documents

Format Type Best Used For Scalability
PDF (.pdf) Vector Plots (Matplotlib, R, Julia), flowcharts, schematics Infinite without quality loss
PNG (.png) Raster (Lossless) UI screenshots, pixel art, high-contrast diagrams Fixed resolution (use 300+ DPI)
JPG / JPEG (.jpg) Raster (Lossy) Photographs, microscope captures, real-world scenes Compression artifacts around text
EPS (.eps) Vector Legacy workflows (auto-converted to PDF by pdfLaTeX) Scalable

Best Practice: Always omit file extensions in \includegraphics{benchmark}. LaTeX will automatically select the best available format (preferring vector .pdf over raster .png if both exist in the directory).


2. Basic Figure Inclusion & Relative Scaling

A professional document should never use hardcoded absolute dimensions (such as width=6cm) because page margins, orientation, and column layouts change across templates. Instead, scale images relative to LaTeX layout registers.

The Canonical Figure Structure

\documentclass{article}
\usepackage{graphicx}

\begin{document}

\begin{figure}[htbp]
  \centering
  \includegraphics[width=0.85\linewidth, keepaspectratio]{convergence_plot}
  \caption{Training loss convergence across 500 epochs on the evaluation dataset.}
  \label{fig:convergence}
\end{figure}

As shown in Figure~\ref{fig:convergence}, the model stabilizes after epoch 120.

\end{document}

Essential \includegraphics Options

Multiple transformation keys can be combined as a comma-separated list inside the brackets [...]:

  • width=0.8\textwidth: Sets the width to 80% of the text block width. In single-column layouts, \textwidth and \linewidth are equivalent; in multi-column environments or nested lists, prefer \linewidth.
  • height=5cm: Sets an explicit height constraint.
  • keepaspectratio: Ensures the image does not stretch or distort when both width and height are specified.
  • angle=90: Rotates the image counter-clockwise by 90 degrees.
  • trim=left bottom right top, clip: Crops image borders by specified dimensions (e.g., trim=10 20 10 20, clip).
% Scaled to 70% column width, rotated 45 degrees, preserving aspect ratio:
\includegraphics[width=0.7\linewidth, angle=45, keepaspectratio]{system_diagram}

3. Demystifying Float Placement: Why Figures “Jump”

One of LaTeX’s most misunderstood mechanics is the floating environment (\begin{figure}).

LaTeX treats figures as “floats”—unbroken typographic blocks that cannot be split across page breaks. When a figure does not fit on the remainder of the current page, TeX’s layout algorithm moves it to a float queue and continues typesettting the following paragraphs to avoid leaving huge blank gaps.

Float Specifiers: [htbp] Explained

You instruct LaTeX’s float engine using bracketed placement specifiers:

\begin{figure}[htbp]

These letters signify priority permissions:

  • h (here): Place the float approximately at the current point in text (if it fits).
  • t (top): Place the float at the top of a page.
  • b (bottom): Place the float at the bottom of a page.
  • p (page): Place the float on a dedicated page containing only floats.
  • ! (override): Relaxes internal TeX float limits (such as maximum float area per page), forcing LaTeX to attempt placement more aggressively.

Rule of Thumb: Never use bare [h]. A single [h] gives the compiler zero alternatives if the float cannot fit on the current page, forcing it to defer the figure to the very end of the document. Always supply flexible fallbacks: [htbp] or [!ht].

Forcing Fixed Placement with [H]

If your editorial guideline strictly requires that an image never float away from its text anchor, import the float package and specify uppercase [H]:

\usepackage{float}

% Later in document:
\begin{figure}[H]
  \centering
  \includegraphics[width=0.9\linewidth]{circuit_schematic}
  \caption{Non-floating circuit diagram placed strictly inline.}
  \label{fig:circuit}
\end{figure}

The [H] specifier removes the figure from the float queue entirely, treating it as an immovable block right where it appears in your source code.


4. Modern Side-by-Side Subfigures with subcaption

Scientific papers frequently require grouping related plots side-by-side with separate labels like (a), (b), and (c).

Warning: Obsolete Packages to Avoid

Before writing code, avoid legacy packages frequently referenced in outdated forum answers:

  • subfigure (1993): Completely obsolete and unmaintained. Causes immediate syntax conflicts with modern caption engines.
  • subfig (2005): Deprecated. Causes known package conflicts with caption and hyperref.

The official, universally accepted standard is subcaption:

\usepackage{subcaption}

Two Figures Side-by-Side (1x2 Grid)

Each subfigure is represented by a \begin{subfigure} environment. Allocate a width to each block (e.g., 0.48\linewidth) and separate them with \hfill to push them to the left and right margins:

\begin{figure}[htbp]
  \centering
  \begin{subfigure}[b]{0.48\linewidth}
    \centering
    \includegraphics[width=\linewidth]{loss_curve}
    \caption{Training loss over iterations.}
    \label{subfig:loss}
  \end{subfigure}
  \hfill
  \begin{subfigure}[b]{0.48\linewidth}
    \centering
    \includegraphics[width=\linewidth]{accuracy_curve}
    \caption{Validation accuracy over iterations.}
    \label{subfig:accuracy}
  \end{subfigure}
  \caption{Model training dynamics on the CIFAR-100 benchmark.}
  \label{fig:training_dynamics}
\end{figure}

In the compiled document:

  • The subfigures appear side-by-side with automatic (a) and (b) labels.
  • You can cross-reference the entire group with Figure~\ref{fig:training_dynamics}.
  • You can cross-reference specific panels with Figure~\ref{subfig:accuracy} (rendering as Figure 1b).

Four Figures in a 2x2 Grid

To create multiple rows, insert a blank line (or \par) between subfigure groups, adding vertical spacing with \vspace{...}:

\begin{figure}[htbp]
  \centering
  % Row 1
  \begin{subfigure}[b]{0.48\linewidth}
    \includegraphics[width=\linewidth]{sample_1}
    \caption{Input image}
    \label{subfig:sample1}
  \end{subfigure}
  \hfill
  \begin{subfigure}[b]{0.48\linewidth}
    \includegraphics[width=\linewidth]{sample_2}
    \caption{Edge detection}
    \label{subfig:sample2}
  \end{subfigure}

  \vspace{0.75em} % Vertical space between rows

  % Row 2
  \begin{subfigure}[b]{0.48\linewidth}
    \includegraphics[width=\linewidth]{sample_3}
    \caption{Segmentation mask}
    \label{subfig:sample3}
  \end{subfigure}
  \hfill
  \begin{subfigure}[b]{0.48\linewidth}
    \includegraphics[width=\linewidth]{sample_4}
    \caption{Final reconstruction}
    \label{subfig:sample4}
  \end{subfigure}

  \caption{Pipeline stages for optical character recognition.}
  \label{fig:ocr_pipeline}
\end{figure}

5. The Critical Rule: \label MUST Follow \caption

One of the most persistent bugs in LaTeX authoring occurs when cross-references resolve to the wrong number:

As shown in Figure 2, the pipeline is evaluated...
% But clicking the link jumps to Section 2 instead of Figure 1!

The Root Cause

In LaTeX, the \refstepcounter command that increments the figure counter and generates the hyperlinked target is triggered by \caption, NOT by \begin{figure}.

% INCORRECT: \label is placed before \caption
\begin{figure}[htbp]
  \label{fig:my_plot} % <--- WRONG! Captures previous section number
  \centering
  \includegraphics[width=0.8\linewidth]{plot}
  \caption{Benchmark results.}
\end{figure}

% CORRECT: \label is placed after (or inside) \caption
\begin{figure}[htbp]
  \centering
  \includegraphics[width=0.8\linewidth]{plot}
  \caption{Benchmark results.}
  \label{fig:my_plot} % <--- CORRECT! Captures the figure counter
\end{figure}

Always place your \label{...} immediately after the \caption{...} command, or embed it directly inside: \caption{Benchmark results.\label{fig:my_plot}}.


6. Two-Column Spanning with figure*

When writing academic papers for IEEE, ACM, or Nature, documents are almost always formatted in two columns (\documentclass[twocolumn]{article}).

In a two-column document:

  • \begin{figure}: Confines the float to the width of a single column (\columnwidth).
  • \begin{figure*}: Spans the float across both columns across the entire page width (\textwidth).
% Full-width wide figure in a two-column paper:
\begin{figure*}[t]
  \centering
  \includegraphics[width=0.95\textwidth]{broad_architecture}
  \caption{High-level architectural pipeline spanning both columns of the IEEE proceedings.}
  \label{fig:broad_arch}
\end{figure*}

Two-Column Float Nuance: Standard LaTeX can only place starred double-column floats (figure* and table*) at the top of a page ([t]) or on a float page ([p]). Specifiers like [b] and [h] are ignored by the core engine for figure*.


7. Placement Cheat Sheet & Troubleshooting

Specifier Placement Target Notes / Gotchas
h Here Unreliable on its own; always pair with [htbp]
t Top of page Preferred default position in academic style guides
b Bottom of page Allowed in single-column; ignored by figure*
p Dedicated float page Triggered automatically when floats are large
! Relaxed constraints Overrides LaTeX’s default maximum page fill fractions
H Exact location Requires \usepackage{float}; disables floating entirely

Quick Troubleshooting Guide

  1. Figure appears at the very end of the document:
    • Cause: The figure is too large to satisfy TeX’s \topfraction or \textfraction parameters.
    • Fix: Reduce width=0.7\linewidth or add [!htbp] to relax restrictions.
  2. Subfigures appear stacked vertically instead of side-by-side:
    • Cause: The combined width of the subfigures exceeds 1.0\linewidth, or there is an accidental blank line between \end{subfigure} and \begin{subfigure}.
    • Fix: Ensure widths sum to $\le 0.98\linewidth$ (accounting for spaces) and use \hfill without blank lines.
  3. \ref prints the section number:
    • Cause: \label was placed before \caption.
    • Fix: Move \label directly below \caption.

Conclusion & Next Steps

High-quality figures make technical papers compelling and legible. By combining graphicx for relative scaling, subcaption for sub-panels, and standard [htbp] placement flags, you have full control over your document layout.

If you need to quickly preview, test, or generate standalone vector illustrations, equation graphics, or TikZ plots for your research slides and papers, check out our LaTeX to Image Converter. It renders math and graphics in your browser with instant SVG and high-DPI PNG export.

Tags:#latex#figures#graphicx#subcaption#document-layout