3

I'm working with knitr

Is it possible to reference data from a figure in the paper?

I have a code chunk that produces a figure in the appendix of my paper. I know how to reference the figure itself

"figure 5 shows a histogram..."

with

"figure \ref{fig:hist_fig} shows a histogram..." 

and, in the appendix,

\begin{figure}
<<hist_fig, cache=FALSE, echo=F>>=
require(ggplot2)
@
\caption{\label{fig:hist_fig} An example histogram} 
\end{figure}

with another R file that starts with # ---- hist_fig ---- and contains the data that produces the histogram, mean, and variance.

but is it possible to reference data from the figure in the paper as well? For instance "figure 5 has a mean of 6 and a variance of 3."

Would this method work for randomly generated data sets that aren't the same on each run?

2 Answers2

1

You can cache the later code chunk (cache = TRUE) and use knitr::load_cache() to fetch the object in the chunk. See the help page ?knitr::load_cache for more info.

Yihui Xie
  • 2,805
1

Here is a simple but less powerful solution. It would be my preference because it avoids caching (which is very hard to get right every time). The downside is that you have to keep track of the chunks (though if you don't you'll probably get an error).

Note that I'm using assign, which is generally frowned upon. I think it's justified here though.

\documentclass{article}

\begin{document}

<<figure_data>>=
figure_data <- function(.data){
  current_chunk_label <- knitr::opts_current$get(name = "label")
  assign(paste0(current_chunk_label, "_data"),
         list(mean = mean(.data), variance = var(.data)), 
         inherits = TRUE)
}
@

<<hist_fig, fig.show='hide'>>=
library(magrittr)
rnorm(100) %T>%
  figure_data %>%
  hist
@
Figure \ref{fig:hist_fig} shows a histogram with mean \Sexpr{hist_fig_data$mean} 
and variance \Sexpr{hist_fig_data$var}.

\appendix
\begin{figure}
\caption{}\label{fig:hist_fig}
\includegraphics{figure/hist_fig-1}
\end{figure}


\end{document}
Hugh
  • 2,374
  • 17
  • 30