[Tex/LaTex] putting a tikzpicture inside a \caption{}

captionstikz-pgf

I'm attempting to put a small tikzpicture inside a \caption{} belonging to a figure environment. The reason for doing this is fairly simple – to create an in-caption legend for a PGFplot, with consistency between the TikZ styles in the figure and in the caption. Previously I would have done this using dashes and the xcolor package, however, this is an awful hack. In this MWE:

\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{figure}
\caption{\raisebox{0.5ex}{
\begin{tikzpicture}\draw[dashed,color=red,thick] (0,0) -- (0.5,0);\end{tikzpicture}}
Gas--Phase} 
\end{figure}
\end{document}

The expected output:

an example of my expected output

is generated, but I get ! Argument of \@caption has an extra }. and ! Paragraph ended before \@caption was complete. Within the larger context of the document that I'm writing, which includes chapters in external .tex files, compilation fails catastrophically (dozens of errors) with no output, so I can't just ignore the warnings in this instance. Any ideas?

Best Answer

PGFplots has this feature built-in already: You can assign \labels to your plots, and then use \ref in the figure caption (or anywhere else) to get a legend picture:

\documentclass{article}
\usepackage{pgfplots}
\begin{document}
\begin{figure}\centering
\begin{tikzpicture}
\begin{axis}
\addplot [red, dashed, thick] {x+rand}; \label{gasphase}
\addplot [black] {x}; \label{straightline}
\end{axis}
\end{tikzpicture}
\caption{A simple diagram: \ref{gasphase} Gas--Phase;  \ref{straightline} A straight line}
\end{figure}
\end{document}