Skip to content

Instantly share code, notes, and snippets.

@jecs
Last active June 10, 2025 22:11
Show Gist options
  • Save jecs/60ab50ea5951f6c1ceba48e4c082878a to your computer and use it in GitHub Desktop.
Save jecs/60ab50ea5951f6c1ceba48e4c082878a to your computer and use it in GitHub Desktop.
Using tikzscale package with pgfplots figure containing subcaptions and labels

Problem

The tikzscale package overloads the \includegraphics command, uses a bounding box to calculate the size of a pgfplots plot, and adjusts the size of the plot such that the target height and width are met, while preserving font sizes. This approach works well unless you have \subcaption{} and \label{} embedded in the figure, which results in multiply-defined labels.

Workaround

  1. Add the following code to your preamble. <unique name> should be replaced by an appropriate toggle name. \newtoggle should be repeated for every figure containing a plot, each with a unique name.
\usepackage{etoolbox}
\newtoggle{<unique name>}
  1. In the tikzpicture environment, change \subcaption{<subcaption text> \label{<label>}} to
\nottoggle{<unique name>}{\parbox{<width>}{\subcaptiontext*[<id>]{<subcaption text>}}}{\subcaption{<subcaption text> \label{<label>}}}

<id> refers to an integer counting up from 1, one for each subcaption.

  1. After the \end{figure} of the corresponding figure, append \toggletrue{<unique name>}.

After following these steps, you should be able to compile the document, hopefully without the multiply-defined labels warning.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment