# Reference in latex document to part of Matplotlib (pgf) generated figure

I have a Python script which draws a plot similar to this:

fig = plt.figure()
ax = plt.axes()

x = np.linspace(-2,2,10)
y = x**2

ax.plot(x, y, label='$x^2$', color="#07529a", linewidth=2.0) #  <--  \label this here ???

plt.legend(loc='upper left')
fig.savefig("../plot.pgf", bbox_inches='tight')
plt.show()


Now I include the figure with this lines in LaTeX:

\begin{figure}[h!]%
\centering
\input{plot.pgf}
\caption{Plot info}
\label{fig:plot}
\end{figure}


Furthermore, I would like to describe the plotted function and add a reference to the plotted line (something like this: \ref{fig:plot:axplot} or this: Use symbols with \label and \ref in custom legend). Is it possible?

Here is one way to do it, with explanation below.

Python file:

import matplotlib.pyplot as plt
from matplotlib import rcParams
import numpy as np

rcParams['text.usetex'] = True
rcParams['pgf.preamble'] = [ r'\newcounter{axes}',
r'\renewcommand{\theaxes}{(\arabic{axes})}'

fig = plt.figure()
ax = plt.axes()

x = np.linspace(-2,2,100)
y = x**2

ax.plot(x, y, label=r'\axeshead $x^2$\label{ax:x2}', color="#07529a", linewidth=2.0)

plt.legend(loc='upper left')
fig.savefig("plot.pgf", bbox_inches='tight')


LaTeX code

\documentclass{article}

\usepackage{unicode-math}
\usepackage{tikz}

\newcounter{axes}[figure]

\renewcommand{\theaxes}{(\arabic{axes})}

\begin{document}

\begin{figure}
\centering
\input{plot.pgf}
\caption{Plot info}
\label{fig:plot}
\end{figure}

The graph \ref{ax:x2} in Figure~\ref{fig:plot}.

\end{document}


On the latex side, you need to set up a counter that may be used to refer to the axes. I have done this with

\newcounter{axes}[figure]


which creates the counter axes, that is reset at each figure. (Be careful, strictly it is reset each time the figure counter is stepped which is trigged by the \caption command.)

I introduce a command \axeshead which is inserted into the label of the ax.plot directive. The definition steps the axes counter and prints a visible label, whose format is controlled by \theaxes. These definition needs to be duplicate in the python file in the 'pgf.preamble'. Now you can just place your \label command inside the label argument of ax.plot and \reference it your latex file.