Recently, I wanted to reference an equation in a LaTeX document from a figure created using matplotlib. Luckily, matplotlib has a PGF backend that makes this possible. Here’s an example:





    e^{i\pi} + 1 = 0

    \caption{This is the caption.}


So we have an labeled equation, and we’d like to create the file figure.pgf so that the equation can be referenced in the figure.

import numpy as np
import matplotlib as mpl
pgf_with_custom_preamble = {
"text.usetex": True,    # use inline math for ticks
"pgf.rcfonts": False,   # don't setup fonts from rc parameters
"pgf.preamble": [
    "\\usepackage{amsmath}",         # load additional packages
import matplotlib.pyplot as plt

plt.plot(np.random.randn(10), label="Equation \\eqref{eq:foo}")
plt.savefig("figure.pgf", bbox_inches="tight")

I’ve borrowed some of the settings from the matplotlib pgf page. You can apparently get quite deep into the pgf settings in matplotlib (see here for example).

Now, finally run,

pdflatex main
pdflatex main

That not a typo — you must run pdflatex twice to get the references correct. Here’s the output:

Further, if you add \usepackage{hyperref} to main.tex, the equation reference in the figure is hyperlinked to the equation itself!