This section of the R Markdown Cookbook shows how to create a plot and to display it later in the document:
---
output: bookdown::pdf_document2
---
We generate a plot in this code chunk but do not show it:
```{r cars-plot, dev='png', fig.show='hide'}
plot(cars)
```
After another paragraph, we introduce the plot:
`)
The problem I have is that I can't reference this plot in the text. See the following code and output:
---
output: bookdown::pdf_document2
---
We generate a plot in this code chunk but do not show it:
```{r cars-plot, dev='png', fig.show='hide'}
plot(cars)
```
Here's a reference to this plot: figure \@ref(fig:cars-plot).
After another paragraph, we introduce the plot:
`)
Note that if I display the plot immediately, the reference works well:
---
output: bookdown::pdf_document2
---
We generate a plot in this code chunk but do not show it:
```{r cars-plot, fig.cap="A nice plot."}
plot(cars)
```
Here's a reference to this plot: figure \@ref(fig:cars-plot).
How can display the plot later but still be able to reference it? I know that I could simply move the chunk where I want the plot to appear but this is not ideal in my case.
Use ref.label
in a later chunk and refer to the later chunk name in the figure reference.
---
output: bookdown::pdf_document2
---
We generate a plot in this code chunk but do not show it:
```{r cars-plot, dev='png', fig.show='hide'}
plot(cars)
```
Here's a reference to this plot: figure \@ref(fig:cars-plot-show).
After another paragraph, we introduce the plot:
```{r cars-plot-show, ref.label="cars-plot", fig.cap="A Nice Plot"}
```