# pgfplots, custom legend and tikz library external

I try to create Tikz figure with several pgfplots subplots. I want to have one legend for them since they all have the same curves. I found out from this question that i can label and than reference each curve. I used that to create simple legend at the bottom of the subplots. And it looked just fine when I tried it as a separate file. Then I put it in my thesis where I use the Tikz external library which solves the TeX memory problem I encountered before because I have many plots. The problem that occurs can be reproduced by this MWE:

\documentclass{article}
\usepackage{pgfplots}
\usetikzlibrary{external}
\tikzexternalize
\begin{document}
\begin{tikzpicture}
\begin{axis}
\addplot coordinates { (0,0) (1,1) };\label{plot:p1}
\end{axis}
\node (A) at (1,-1) {\ref{plot:p1} Plot 1};
\end{tikzpicture}
\end{document}


which produces:

(I'm using just one plot here instead of subplots for simplicity). Notice the question marks for the missing reference in the first image. Of course, if I comment out the 4th line (don't use externalize) the reference turns out just fine (the second image). So I wonder:

How can I get the reference and still use externalize?

P.S.: TexLive 2011 on Ubuntu 11.10

-
Section 7.1.1 Using the Automatic Externalization Framework of TikZ from pgfplots manual explains why you have this problem and how to solve it. –  Ignasi Dec 1 '11 at 11:55
possible duplicate of pgfplots: externalization and legend referencing –  Jake May 3 '12 at 8:26

As Ignasi said in the comment, this doesn't work completely automatically.

From the pgfplots manual:

There is just a special case if a \label/\ref drawn as a tikzpicture. This is, for example, the case for the legend \ref images or for the \pgfplotslegendfromname feature. In such cases, you need to proceed as for case a) since mode=convert with system call can't handle that stuff on its own.

Case a) suggests to

consider using mode=list and make or copy{paste the system call for the image(s) and issue it manually.

\pgfkeys{

to the file and run make -B -f <filename>.makefile after the first compile run.