# knitr how to label and call a figure number in a text

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 ...

• You have asked couple questions before, so: Do you know what MWE is? – yo' Mar 1 '13 at 19:30
• Did you compile twice, so that TeX had a chance to read the .aux file that contains the reference information? – Ethan Bolker Mar 1 '13 at 19:30
• @tohecz yes i added my MWE. – S12000 Mar 1 '13 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 '13 at 19:34
• @EthanBolker yeah I compile twice. – S12000 Mar 1 '13 at 19:40

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:

\documentclass{article}
\begin{document}

<<myfig, fig.cap=''>>=
plot(1:10)
@

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

\end{document}


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

\begin{knitrout}
\begin{alltt}
\hlfunctioncall{plot}(1:10)
\end{alltt}
\end{kframe}\begin{figure}[]

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

\end{knitrout}

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


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