[Tex/LaTex] Specify legend entry as \addplot option

legendpgfplots

Somehow, specifying the legend entry for each \addplot using the separate command \addlegendentry bothers me… I'm not sure why, probably because my sense of order says that the legend entry belongs to the plot, and thus should be part of the plot definition. That way I could for example comment out a plot without the legend entries for the other plots getting messed up due to the order of the plots being changed.

So is it safe to define a key to do that, or are there possible (TeXnical, pragmatic or ideological) issues with this that I haven't thought of?

\documentclass{standalone}
\usepackage{pgfplots}
\pgfkeys{/pgfplots/legend entry/.code=\addlegendentry{#1}} % <-- this
\begin{document}
\begin{tikzpicture}
\begin{axis}
    \addplot[legend entry=$x$] {x}; 
    \addplot[legend entry=$x^2$] {x^2}; 
\end{axis}
\end{tikzpicture}
\end{document}

As percusse pointed out in the comments, it breaks when not specifying the key on some of the plots, but in a very weird way:

\addplot[red,legend entry=$10x$] {10*x};
\addplot[green] {x^2};
\addplot[blue,legend entry=$x^3$] {x^3};

Messed up labels

Why does it repeat the first label on the last plot? Of course, the second plot should be removed from the legend by using forget plot, even when using \addlegendentry, but that doesn't explain why an entry is added for the third plot at all.

Best Answer

The answer as such is "there is no such feature in pgfplots".


Implementing such a feature is not too difficult, but requires some care to handle plots without a legend entry: you would need to remember the value and check if the current plot has a value.

The following appears to work:

\documentclass{standalone}
\usepackage{pgfplots}
\pgfplotsset{
    legend entry/.initial=,
    every axis plot post/.code={%
        \pgfkeysgetvalue{/pgfplots/legend entry}\tempValue
        \ifx\tempValue\empty
            \pgfkeysalso{/pgfplots/forget plot}%
        \else
            \expandafter\addlegendentry\expandafter{\tempValue}%
        \fi
    },
}

\begin{document}
\begin{tikzpicture}
\begin{axis}
    \addplot[red,legend entry=$x$] {x}; 
    \addplot[green] {x^2};
    \addplot[yellow,legend entry=$x^3$] {x^3}; 
\end{axis}
\end{tikzpicture}
\end{document}
\end{document}

Note that your solution replicates the legend entry because the keys are assigned (at least) twice: once during the survey phase and at least once during the visualization phase.

enter image description here