[Tex/LaTex] Legend referencing in caption *and* externalization

captionscross-referencinglegendpgfplots

I am trying to make a reference to a plot inside a figure's caption
while using the externalize library.

The issue of plot reference using externalization has already been
raised in this question.
I decided notto externalize the references images and defined the
following command:

\newcommand{\plotref}1{\tikzexternaldisable\ref{#1}\tikzexternalenable}

Then, the following code with the reference outside the caption works :

\documentclass{article}

\usepackage{pgfplots}
\usepackage{pgfplotstable}
\usepackage{tikz}
\usetikzlibrary{external}
\tikzexternalize[prefix=tikz/,shell escape=-enable-write18]

\newcommand{\plotref}[1]{\tikzexternaldisable\ref{#1}\tikzexternalenable}

\begin{document}

\begin{figure}
  \centering
  \tikzset{external/remake next}
  \tikzsetnextfilename{figname}
\begin{tikzpicture}[baseline]

  \pgfplotstableread{
    1 4   
    2 4.2 
    3 3.1 
    4 2.5 
  }\table

\begin{axis}[width=5cm,height=5cm]

\addplot table[x index=0,y index=1]{\table};\label{LAB}

\end{axis}
\end{tikzpicture}
  \caption{You must defeat Sheng Long to stand a chance.}
  \label{dummy}
\end{figure}

Xyzzy ! \plotref{LAB} happens.

\end{document}

I have seen in this question
that legend in caption are normally possible.
However, the following code with the reference inside the caption does not work :

\documentclass{article}

\usepackage{pgfplots}
\usepackage{pgfplotstable}
\usepackage{tikz}
\usetikzlibrary{external}
\tikzexternalize[prefix=tikz/,shell escape=-enable-write18]

\newcommand{\plotref}[1]{\tikzexternaldisable\ref{#1}\tikzexternalenable}

\begin{document}

\begin{figure}
  \centering
  \tikzset{external/remake next}
  \tikzsetnextfilename{figname}
\begin{tikzpicture}[baseline]

  \pgfplotstableread{
    1 4   
    2 4.2 
    3 3.1 
    4 2.5 
  }\table

\begin{axis}[width=5cm,height=5cm]

\addplot table[x index=0,y index=1]{\table};\label{LAB}

\end{axis}
\end{tikzpicture}
  \caption{Xyzzy ! \plotref{LAB} happens.}
  \label{dummy}
\end{figure}

You must defeat Sheng Long to stand a chance.

\end{document}

It raises the following error message

! Incomplete \iffalse; all text was ignored after line 35.

\fi

that I fail to interpret.

An alternative to not externalizing the small reference images has
been proposed in this question
but I did not understand how to implement it and don't know if this
would solve my problem.

Do you know how to make plot references in caption and use
externalization ?


Side note: it sometimes simpler and more effective to do things manually. See this question for similar results, not automatic but somehow more straightforward.

Best Answer

You should write \protect\plotref{LAB} in your caption. I suppose that it is an expansion issue; your \plotref command is "fragile" in terms of LaTeX, and "fragile" commands need to be \protected inside of captions, section titles etc.