Knitr: how to reference a plot from a multi-line fragment

I have a .Rnw document where I want to reference a plot from a multi-line fragment. How to do it?

Example:

 \documentclass{article} \begin{document} <<single_chunk, fig.cap="hi">>= plot(1:5) @ I can reference this single chunk fine! See \ref{fig:single_chunk}. <<multichunk, fig.cap="hello">>= plot(1:10) plot(10:1) @ The first figure is great, but \ref{fig:multichunk}. Try again \ref{fig:multichunk-1}. \end{document} 

Both of these attempts lead to ?? .

+6
source share
1 answer

Just look at the generated * .tex file! Here's the relevant part (I took the freedom to level it a little better than knit ):

 \begin{knitrout} \definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe} \begin{alltt} \hlkwd{plot}\hlstd{(}\hlnum{1}\hlopt{:}\hlnum{10}\hlstd{)} \end{alltt} \end{kframe} \begin{figure} \includegraphics[width=\maxwidth]{figure/multichunk-1} \caption[hello]{hello} \label{fig:multichunk1} \end{figure} \begin{kframe}\begin{alltt} \hlkwd{plot}\hlstd{(}\hlnum{10}\hlopt{:}\hlnum{1}\hlstd{)} \end{alltt} \end{kframe} \begin{figure} \includegraphics[width=\maxwidth]{figure/multichunk-2} \caption[hello]{hello} \label{fig:multichunk2} \end{figure} 

So, if you look carefully, you will notice that the multiplier numbers are called fig:multichunk1 and fig:multichunk2 . Indeed, if you refer to these ( \ref{fig:multichunk1} , ...), everything works fine.

+3
source

Source: https://habr.com/ru/post/985739/


All Articles