Plot legend in figure caption

If you have a plot and add names to the data series with \addlegendentry{}, a legend is added to the plot that specifies the names for the lines or bars. This is an example plot from my thesis:

\begin{figure}
\begin{tikzpicture}
\begin{axis}[myplot]
\addplot plot coordinates {(1, 0.17) (2, 0.13) (3, 0.09) (4, 0.06) (5, 0.01) (6, 0.01)};
\addlegendentry{System1} % for legend
\addplot plot coordinates {(1, 0.13) (2, 0.16) (3, 0.16) (4, 0.14) (5, 0.14) (6, 0.13)};
\addlegendentry{System2} % for legend
\end{axis}
\end{tikzpicture}
\caption{Results (Precision) at different $k$ for the two systems}
\end{figure}

You can influence the placement and appearance of the legend and it looks really professional. Most of the time that will be exactly what you want. But not always. I wanted the legend to be embedded in the text of the caption (long story why). And this is possible and even quite simple! You just need to define a label for the data series and when you refer to that label, a picture of the line and marker is drawn as the reference.

\begin{figure}
\begin{tikzpicture}
\begin{axis}[myplot]
\addplot plot coordinates {(1, 0.17) (2, 0.13) (3, 0.09) (4, 0.06) (5, 0.01) (6, 0.01)};
\label{tikz:System1}
%\addlegendentry{System1} % remove to get rid of legend
\addplot plot coordinates {(1, 0.13) (2, 0.16) (3, 0.16) (4, 0.14) (5, 0.14) (6, 0.13)};
\label{tikz:System2}
%\addlegendentry{System2}
\end{axis}
\end{tikzpicture}
\caption{Results (Precision) at different $k$ for the two systems \ref{tikz:System1} System 1 and \ref{tikz:System2} System 2}
\end{figure}

Pgfplots is cool!

Hat tip: Stackexchange (the question is about something else)

This entry was posted in LaTeX and tagged , , , by swk. Bookmark the permalink.

About swk

I am a software developr, data scientist, computational linguist, teacher of computer science and above all a huge fan of LaTeX. I use LaTeX for everything, including things you never wanted to do with LaTeX. My latest love is lilypond, aka LaTeX for music. I'll post at irregular intervals about cool stuff, stupid hacks and annoying settings I want to remember for the future.