pluke pluke - 2 months ago 15
R Question

R markdown linking to a figure

I am creating a report with multiple figures and tables. I'd like to refer to them in the accompanying text. I've tried the following:

---
title: "Test"
output:
pdf_document
---
Figure \ref{test} is a graph

```{r test, fig.cap="This is a graph"}

df <- data.frame(gp = factor(rep(letters[1:3], each = 10)),
y = rnorm(30))

ggplot(df, aes(x = gp, y = y)) +
geom_point()
```

This is text to follow the diagram

\pagebreak

This is another page but can still link to Figure \ref{test}


But the result is:

Figure ?? is a graph
...
This is another page but can still link to Figure ??


Is there a default way to do this in R markdown without having to write functions myself

Sam Sam
Answer

I think I found an answer here- https://github.com/yihui/knitr/issues/323

Using this code seemed to provide the behavior I think you're looking for, if I'm understanding correctly.

---
title: "Test"
output: 
  pdf_document
---
Figure \ref{fig:plot} is a graph

```{r plot-ref, fig.cap = "This is a graph\\label{fig:plot}"}

library('ggplot2')

df <- data.frame(gp = factor(rep(letters[1:3], each = 10)),
                 y = rnorm(30))

ggplot(df, aes(x = gp, y = y)) +
   geom_point()
```

This is text to follow the diagram

\pagebreak

This is another page but can still link to Figure \ref{fig:plot}
Comments