[Tex/LaTex] Knitr: How to make a crossreferences to figures and tables generatrd by code chunks

cross-referencinghyperrefknitrlabels

I would like to make cross-references to images and tables generated from knitr code chunk in the same way as to standard figures and tables. In a standard figure I use control sequence \label, but i don`t know how to put it into a code chunk. (My document contains also standard figures. Therefore I want to have one numbering of all figures and other one for all tables, no matter how they were generated.)

My code:

\documentclass[a4paper,12pt, english]{article}
\usepackage[colorlinks=true,
            linkcolor=gray,
            urlcolor=blue,
            citecolor=gray,
            ]{hyperref}
\usepackage{graphicx}

\begin{document}
<<chunk_image, results="asis">>=
plot(iris)
@

<<chunk_table, results="asis">>=
library(xtable)
print(xtable(head(iris)))
@

Some text about the image (see \autoref{chunk_image})
\\ Some text about the table (see \autoref{chunk_table})
\end{document}

The outptut I want to get:

Some text about the image (see Figure 1)
Some text about the table (see Table 1)

Best Answer

There are two approaches to this.

Approach 1. Set the label inside TeX, and use R only to generate the body of the figure or table. For example,

\begin{figure}
\begin{center}
<<image,echo=FALSE>>= 
boxplot(na.omit(iris))
@ 
\end{center}
\caption{Iris Boxplot}
\label{fig:iris}
\end{figure}

Note that caption and label are defined inside TeX.

Approach 2. Generate labels and captions inside R, and send them to TeX. For example,

<<table,results='asis', echo=FALSE>>=
library(xtable)
print(xtable(head(iris),caption='Iris table',label='tab:iris'))
@ 

Here we do not put \begin{table}...\end{table}, \caption or \label in TeX file, since xtable does it for us.

Note that knitr generates figure labels for you if you use fig.cap option, for example, the chunk

<<my_chunk, fig.cap='Iris plot'>>=
plot(iris)
@

will have \begin{figure}...\end{figure} inserted with the label fig:my_chunk.

In both cases you can refer to these labels in the usual way:

See Figure~\ref{fig:iris} and Table~\ref{tab:iris}.

You can mix these approaches in the same file, provided that each figure or table uses either the first or the second approach.