As a knitr beginner I don't know how to label a figure and call it.

For my first figure I've tried the following code witouth succes...

<<fig.cap="Dendrogram of GDP (2000-2012)",fig.lp="fig:test">>=  
plot(HClust.1, main= "Cluster Dendrogram GDP")

As you can see the figure \ref{fig:test} shows that...

But after compilation I get figure ?? instead figure 1 ...

  • 1
    You have asked couple questions before, so: Do you know what MWE is?
    – yo'
    Mar 1, 2013 at 19:30
  • Did you compile twice, so that TeX had a chance to read the .aux file that contains the reference information? Mar 1, 2013 at 19:30
  • @tohecz yes i added my MWE.
    – S12000
    Mar 1, 2013 at 19:33
  • Well, you show a one line of a TeX code, which is not a MWE. It might have happened that we have edited almost at the same time and your edit got suppressed, could you please check it? Thanks
    – yo'
    Mar 1, 2013 at 19:34
  • @EthanBolker yeah I compile twice.
    – S12000
    Mar 1, 2013 at 19:40

1 Answer 1


fig.lp is not the label of the figure, it is the prefix that is used to create the label. From the description of knitr options

fig.lp: ('fig:'; character) label prefix for the figure label to be used in \label{}; the actual label is made by concatenating this prefix and the chunk label, e.g. the figure label for <<foo-plot>>= will be fig:foo-plot by default

If you don't give your chunks names, they will get a default name such as unnamed-chunk-1 where the number depends on where it is in the file (and so would make for a bad label to target).

Additionally, to get the graphics into a figure environment, you need to give it a caption. Again from the options description

fig.cap: (NULL; character) figure caption to be used in a figure environment in LaTeX (in \caption{}); if NULL or NA, it will be ignored, otherwise a figure environment will be used for the plots in the chunk (output in \begin{figure} and \end{figure})

Without this there is no figure environment and therefore no \label{} created.

Putting this together, here is a MWE:


<<myfig, fig.cap=''>>=

As you can see the figure \ref{fig:myfig} shows that...


This creates a .tex file, the relevant (but incomplete) excerpt of which is

\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}

\includegraphics[width=\maxwidth]{figure/myfig} \caption[]{\label{fig:myfig}}


As you can see the figure \ref{fig:myfig} shows that...

You can see that the \label{} and \ref{} match up now.

See also more discussion about this in a related Stack Overflow question.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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