Search code examples
rr-markdownbookdown

How to reference a plot that is displayed later with bookdown?


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:

![A nice plot.](`r knitr::fig_chunk('cars-plot', 'png')`)

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:

![A nice plot.](`r knitr::fig_chunk('cars-plot', 'png')`)

enter image description here

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).

enter image description here

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.


Solution

  • 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"}
    
    ```