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}

<<chunk_image, results="asis">>=

<<chunk_table, results="asis">>=

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

The outptut I want to get:

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

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,

\caption{Iris Boxplot}

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>>=
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'>>=

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.


I haven't tried kniter and I couldn't compile the code you are providing. Anyways, it happened for me to write some LaTeX command instead of figures on my papers. I hope you are not using something incompatible with figure environment. A simple example can be this code:

\documentclass[a4paper,12pt, english]{article}


    \centerline{ I have some  text here inside figure}
 \caption{Defined coordinate frames for the macro robot.}

    \centerline{ I have some  text here inside table}
    \caption{Defined coordinate frames for the macro robot.}
    Some text about the image (see \autoref{myfig}) \\
    Some text about the table (see \autoref{mytable})   \\

The output is the same as you are talking about: enter image description here

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.