[Tex/LaTex] pgfplots hand-made legend (\label + \ref) fails with custom styles

cross-referencingpgfplots

In pgfplots, when I use a custom style to plot a line, \label the line and then \ref to this plot, I am unable to get the desired result.

The desired result would be to get a little line where I am using \ref.

The actual result:

  • On the first compilation, I get LaTeX Warning: Reference 'plot:coor' on page 1 undefined on input line 11., and the line in the text gets replaced by ??.
  • The second compilation fails with ! Package pgfkeys Error: I do not know the key '/tikz/custom' and I am going to ignore it. Perhaps you misspelled it..

I'm using:

  • pdfTeX, Version 3.1415926-2.3-1.40.12 (TeX Live 2011)
  • LaTeX2e <2011/06/27>
  • pgfplots 2011/07/29 v1.5 (git show 1.5-1-gcc2f2d2 )
  • tikz 2010/10/13 v2.10 (rcs-revision 1.76).

A minimum (not) working example:

\documentclass{standalone}
\usepackage{tikz}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}[custom/.style={thick}]
\begin{axis}
\addplot[custom] coordinates {(0,0) (1,1) (2,3)};
\label{plot:coor}
\end{axis}
\end{tikzpicture}
This is \ref{plot:coor}.
\end{document}

If I add the custom style to the axis-environment, the problem remains. If I copy the thick to the arguments of addplot, the problem goes away. However, in my real situation, I apply a similar style to four different plots, so I would like to use a custom style. My questions:

  • Is this a bug?
  • If yes, is it known and is there a workaround?
  • If no, how do I \refer to a \labeled plot created with a custom style?
  • Why is it behaving in this way?

Related but different questions:

Best Answer

Correct me if I'm wrong, but I think I realised the answer to my own question.

The reason \ref won't work is because when \ref is invoked, the style defined inside the tikzpicture is no longer known. To make it work, use \pgfplotsset:

\documentclass{standalone}
\usepackage{tikz}
\usepackage{pgfplots}
\begin{document}
\pgfplotsset{custom/.style={thick}}
\begin{tikzpicture}
\begin{axis}
\addplot[custom] coordinates {(0,0) (1,1) (2,3)};
\label{plot:coor}
\end{axis}
\end{tikzpicture} 
This is \ref{plot:coor}.
\end{document}
Related Question