[Tex/LaTex] Ordering of legend vs zorder

pgfplots

Is there a way to specify the order of entries in a pgfplots legend? Right now, I can use legend entries or \addlegendentry to specify the legend label, however the legend order is the same as they appear in the tex file.
Is there a way to specify the order without reordering the plots in the tex file (I would like to keep the same zorder rendering).

Thanks

Best Answer

Demonstrating a couple of possibilities. The last is the most flexible, but also involves the most work.

enter image description here

\documentclass[border=5mm]{standalone}
\usepackage{pgfplots}
\usetikzlibrary{matrix}
\begin{document}
\begin{tikzpicture}
\begin{axis}[reverse legend]
\addplot {x};
\addplot {-x};
\addplot {2*x};
\addplot {-2*x};

\legend{$x$,$-x$,$2x$,$-2x$}
\end{axis}
\end{tikzpicture}
\begin{tikzpicture}
\begin{axis}[legend columns=2,transpose legend]
\addplot {x};
\addplot {-x};
\addplot {2*x};
\addplot {-2*x};

\legend{$x$,$-x$,$2x$,$-2x$}
\end{axis}
\end{tikzpicture}
\begin{tikzpicture}
\begin{axis}[name=aa]
\addplot {x};
\label{a}
\addplot {-x};
\label{b}
\addplot {2*x};
\label{c}
\addplot {-2*x};
\label{d}

\end{axis}
\matrix [
 matrix of nodes,
 nodes={anchor=west},
 anchor=north east,
 at={([shift={(-3pt,-3pt)}]aa.north east)},
 fill=white,
 draw,
 inner sep=2pt,
 row sep=2pt
] {
\ref{b} $-x$ \\
\ref{a} $x$ \\
\ref{d} $-2x$ \\
\ref{c} $2x$ \\
};

\end{tikzpicture}
\end{document}