I find it useful to add
\pgfplotsset{/tikz/every picture/.append style={trim axis left,trim axis right}}
to my preamble for bounding box restrictions. But then when I use the legend to name feature (see attachment) I get the following error:
! Package pgf Error: No shape named current axis is known
How can I fix this?
MWE:
\documentclass{article}
\usepackage{lipsum,pgfplots}
\pgfplotsset{compat=1.7}
\usepgfplotslibrary{external}
\usetikzlibrary{pgfplots.external}
\tikzexternalize[shell escape=-enable-write18]
\pgfplotsset{/tikz/every picture/.append style={trim axis left,trim axis right}}
\begin{document}
\setlength\fboxsep{0pt}
\begin{figure}[h!]\centering
\fbox{\begin{tikzpicture}
\begin{axis}[domain=-2:2,
width=0.5\textwidth,
xlabel={$x$},ylabel={$y$},
%
legend to name=mylegend,
legend columns=-1,
legend entries={$x^2$,$x^3$}]
\addplot {x^2};\addplot {x^3};
\end{axis}
\end{tikzpicture}}%
%
\hspace{1.5cm}%
%
\fbox{\begin{tikzpicture}
\begin{axis}[domain=-2:2,
width=0.5\textwidth,
xlabel={$x$},ylabel={$y$}]
\addplot {x^2};\addplot {x^3};
\end{axis}
\end{tikzpicture}}%
\tikzexternaldisable\ref{mylegend}\tikzexternalenable
% http://tex.stackexchange.com/q/37471/14497
\end{figure}
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Ut purus elit,
vestibulum ut, placerat ac, adipiscing vitae, felis.
\end{document}
