TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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:

\begin{tikzpicture}\draw[dashed,color=red,thick] (0,0) -- (0.5,0);\end{tikzpicture}}

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?

share|improve this question
I think that it would be better to directly put the legends in the plot rather than in the caption. – projetmbc Nov 1 '11 at 10:58
up vote 16 down vote accepted

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:

\addplot [red, dashed, thick] {x+rand}; \label{gasphase}
\addplot [black] {x}; \label{straightline}
\caption{A simple diagram: \ref{gasphase} Gas--Phase;  \ref{straightline} A straight line}
share|improve this answer
Thanks Jake, that works wonderfully. Never spotted that in the manual. – Richard Terrett Nov 1 '11 at 4:34
The solution proposed is smart. – projetmbc Nov 1 '11 at 10:59
Very nice! But what happens if I make my tikzpicture in an external file and call it from within main.tex where the figure environment is located? – HCAI Mar 30 '13 at 12:20
@HCAI: Do you mean that you're putting the tikzpicture into an external .tex file that you include using \input (or \include) (in that case it should just work), or do you mean that you're compiling the tikzpicture into a separate .pdf file using the external library? In that case, things are a bit more complicated. – Jake Mar 30 '13 at 16:58
@Jake The latter. I create a standalone tikzpic.tex file and call it using \input and compile using external library. It's necessary because the pictures are so big. Is it a complicated procedure? – HCAI Mar 30 '13 at 17:34

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.