[Tex/LaTex] Draw tikzpicture in figure caption

captionspgfplotstikz-pgf

I want to make a small tikzpicture inside the caption of a figure, I namely want to create a legend of a plot in the caption. I have read section 4.9.6 Legends with \label and \ref from the pgfplots manual. However I compile my plots to a .pdf file and then insert it in my document, so I cannot use that.

The following minimal example triggers an error ! Argument of \@caption has an extra }

\documentclass{article}                                                         
\usepackage{tikz}                                                               
\begin{document}
\begin{figure}                                                                  
  \caption{test                                                                   
    \begin{tikzpicture}                                                           
      \draw[black] (0pt,0pt) -- (15pt,0pt);                                       
    \end{tikzpicture}                                                             
  }                                                                               
\end{figure}                                                                    
\end{document}

How can I solve this?

Best Answer

I don't see the need for boxes here, you can simply use:

\documentclass{article}                                                         
\usepackage{tikz}    

\newcommand\drawline[1][black]{%
  \begin{tikzpicture}                                                           
    \draw[#1] (0pt,0pt) -- (15pt,0pt);                                       
  \end{tikzpicture}%
}                                              
\begin{document}
\listoffigures

\begin{figure}
\caption{test \drawline[ultra thick]}
\caption{test \drawline[red,dashed]}
\end{figure}                                                                    

\end{document}

enter image description here

Since \drawline has an optional argument, LaTeX protecting mechanism is automatically used; had the definition been given as

\newcommand\drawline[1]{%
  \begin{tikzpicture}                                                           
    \draw[#1] (0pt,0pt) -- (15pt,0pt);                                       
  \end{tikzpicture}%
}                                              

then

\caption{test \drawline{ultra thick}}

would fail on the second run. In this case one would have to use

\caption{test \protect\drawline{ultra thick}}

or, better yet, protect the command from the definition itself:

\DeclareRobustCommand\drawline[1]{%
  \begin{tikzpicture}                                                           
    \draw[#1] (0pt,0pt) -- (15pt,0pt);                                       
  \end{tikzpicture}%
}                                              

(Thanks to Joseph Wright).