[Tex/LaTex] Use symbols with \label and \ref in custom legend

cross-referencinglegendpgfplots

I would like to build a legend entry that refers to two simultaneous plots, because it is more intuitive to do so. I use \label and \ref to refer to the plot symbols, but they are shifted in the legend, while they are not shifted in the text. What am I doing wrong?

\documentclass[10pt]{article}
\usepackage{color}
\usepackage{amssymb}
\usepackage{amsmath} 
\usepackage[utf8]{inputenc}
\usepackage{pgfplots}
\usepackage{pgfplotstable}
\usetikzlibrary{plotmarks}

\begin{document}

\begin{tikzpicture}
 \begin{axis}
  \addlegendimage{empty legend}
  \addlegendentry{\ref{pgf:x} $\le$ \ref{pgf:x2}}
  \addplot+ function {x};
   \label{pgf:x}
  \addplot+ function{x^2};
   \label{pgf:x2}
 \end{axis}
\end{tikzpicture}

The legend is placed \ref{pgf:x2} correctly here

\end{document}

enter image description here

Best Answer

Not sure it is the best way but it appears to work if you reset the tikzpicture locally:

enter image description here

\documentclass[10pt]{article}
\usepackage{color}
\usepackage{amssymb}
\usepackage{amsmath} 
\usepackage[utf8]{inputenc}
\usepackage{pgfplots}
\usepackage{pgfplotstable}
\usetikzlibrary{plotmarks}

\begin{document}

\begin{tikzpicture}
 \begin{axis}
  \addlegendimage{empty legend}
  \addlegendentry{\begin{tikzpicture}\ref{pgf:x}\end{tikzpicture} $\le$ \begin{tikzpicture}\ref{pgf:x2}\end{tikzpicture}}
  \addplot+ function {x};
   \label{pgf:x}
  \addplot+ function{x^2};
   \label{pgf:x2}
 \end{axis}
\end{tikzpicture}

The legend is placed \ref{pgf:x2} correctly here

\end{document}