knitr:如何从多图块中引用图

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

我有一个 .Rnw 文档,我想在其中引用多图块中的一个图。我该怎么做?

示例:

\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}

这两次尝试都会导致 ??

看看生成的*.tex文件吧!这是相关部分(我自由地将其对齐得比 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}

因此,如果您仔细观察,您会注意到多图图形被命名为 fig:multichunk1fig:multichunk2。事实上,如果您引用这些 (\ref{fig:multichunk1}, ...),一切正常。