0
votes

Creating a parameterized report with an rnw file. I am trying to reference specific figures from a code chunk that has multiple figures in it (generated by a loop through a list of figures). I know if there's a single figure I can reference it from the chunk label with \ref{fig:foo} as Yihui mentions in https://bookdown.org/yihui/bookdown/figures.html . But I cannot seem to reference specific figures in the chunk. I tried referencing the unique figure caption or the chunk as a whole but both give me ??. Is there a way to do this?

I searched this Dynamic LaTeX references in R comment with knitr and its linked questions but wasn't able to make it work.

Also in Figures captions and labels in knitr , the plots are combined into one big plot which bypasses the problem.

MVWE:

\documentclass{article}

\usepackage{float}
\usepackage{hyperref}
\usepackage{caption} % Needs to be after hyperref. jumps you to top of figure not to label.

\begin{document}



<<figures, fig.cap=c('fig1','fig2')>>=
library(knitr)
library(markdown)
library(rmarkdown)
library(ggplot2)

figure1 <- ggplot(mtcars) + geom_point(aes(x=mpg,y=cyl))
figure2 <- ggplot(mtcars) + geom_point(aes(x=drat,y=wt))

plots <- list(figure1,figure2)

plots
@


as we can see in \ref{fig:figures}

\end{document}
1

1 Answers

2
votes

Just append a number to it:

as we can see in \ref{fig:figures1} and \ref{fig:figures2}

To figure this out, you should look at the .tex file, which contains

\begin{figure}
\includegraphics[width=\maxwidth]{figure/figures-1} \caption[fig1]{fig1}\label{fig:figures1}
\end{figure}

for the first one, and similar stuff for the other. The \label{fig:figures1} part is what your \ref needs to refer to.