# How can legend entries be obtained from different plots in a groupplot?

I would like to place a legend outside an axis using symbols from multiple plots within a groupplot. Trying it the way I show below doesn't seem to work, just the last entry is shown. How can this be done in a way such that all entries are shown?

\documentclass[crop]{standalone}

\usepackage[svgnames]{xcolor}
\usepackage{pgfplots}
\usepgfplotslibrary{groupplots}

\begin{document}

\begin{tikzpicture}
\begin{groupplot}[
group style={
{group size=2 by 2}},
legend to name=grouplegend]

\nextgroupplot[title=One]

\nextgroupplot[title=Two]

\nextgroupplot[title=Three]

\nextgroupplot[title=Four]

\end{groupplot}

\node (l1) at ($(group c1r2.south)!0.5!(group c2r2.south)$)
[below, yshift=-2\pgfkeysvalueof{/pgfplots/every axis title shift}]
{\ref{grouplegend}};

\end{tikzpicture}

\end{document}


-
I think you're best off posting a feature request for this on Sourceforge. PGFplots is being very actively developed, so there's a good chance of this being implemented relatively fast. –  Jake Jun 19 '12 at 7:14

You can use the /pgfplots/legend to name={<name>} feature described in the manual reference under "Legends outside of an axis". The example quoted is:

% Preamble: \pgfplotsset{width=7cm,compat=1.3}
\pgfplotsset{footnotesize,samples=10}
\begin{center}% note that \centering uses less vspace...
\begin{tikzpicture}
\begin{axis}[
legend columns=-1,
legend entries={$(x+0)^k$;,$(x+1)^k$;,$(x+2)^k$;,$(x+3)^k$},
legend to name=named,
title={$k=1$}]
\end{axis}
\end{tikzpicture}
%
\begin{tikzpicture}
\begin{axis}[title={$k=2$}]
\end{axis}
\end{tikzpicture}
%
\begin{tikzpicture}
\begin{axis}[title={$k=3$}]
\end{axis}
\end{tikzpicture}
\\
\ref{named}
\end{center}


Which produces:

Edit: I guess this doesn't work for group plots. Here's a horrible hack that kinda works:

\documentclass[crop]{standalone}

\usepackage[svgnames]{xcolor}
\usepackage{pgfplots}
\usepgfplotslibrary{groupplots}

\begin{document}

\begin{tikzpicture}
\begin{groupplot}[
group style={
{group size=2 by 2}},
xmin=0,
enlarge x limits=true,
]

\nextgroupplot[title=One, legend to name=grouplegend]

\nextgroupplot[title=Two]

\nextgroupplot[title=Three]

\nextgroupplot[title=Four]

\end{groupplot}

\node (l1) at ($(group c1r2.south)!0.5!(group c2r2.south)$)
[below, yshift=-2\pgfkeysvalueof{/pgfplots/every axis title shift}]
{\ref{grouplegend}};

\end{tikzpicture}

\end{document}


This produces:

-
If I understand the question correctly, this won't work for this case: You can't "collect" plots from different axes using this method. In the question, each axis contains one plot, but the legend should contain four entries (blue, red, gray and orange). –  Jake Jun 15 '12 at 17:23
Ah, I see, d'oh. I've edited the answer with an idea to rectify the situation. –  slurms Jun 15 '12 at 18:02
@Jake is correct. I will look at the edit to see if it works. –  sappjw Jun 18 '12 at 13:34