Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knitr: how to reference a plot from a multi-plot chunk

Tags:

r

knitr

I have a .Rnw document where I want to reference a plot from a multi-plot chunk. How do I do this?

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 these attempts result in ??.

like image 716
CephBirk Avatar asked Apr 23 '15 02:04

CephBirk


People also ask

How do I show plots in R markdown?

In RStudio, when you open a new RMarkdown file, in the editor pane, there is a cogwheel button / menu where you can choose "Chunk Output Inline". That should put the plots into the document.

How do I plot side by side in R markdown?

To place multiple figures side-by-side from the same code chunk, you can use the fig. show='hold' option along with the out. width option. Figure 2.5 shows an example with two plots, each with a width of 50% .

How to not show code in r Markdown?

include = FALSE prevents code and results from appearing in the finished file. R Markdown still runs the code in the chunk, and the results can be used by other chunks. echo = FALSE prevents code, but not the results from appearing in the finished file. This is a useful way to embed figures.


1 Answers

Just have a look at the generated *.tex file! Here's the relevant part (I took the freedom to align it a bit more nicely than knit does):

\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 closely, you'll note that the multiplot figures are named fig:multichunk1 and fig:multichunk2. And indeed, if you reference these (\ref{fig:multichunk1}, ...), everything works fine.

like image 199
jhin Avatar answered Oct 21 '22 02:10

jhin