如何引用稍后用 bookdown 显示的图?

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

This section 的 R Markdown Cookbook 展示了如何创建绘图并稍后在文档中显示它:

---
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')`)

我遇到的问题是我无法在文中引用这个情节。看下面的代码和输出:

---
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')`)

请注意,如果我立即显示绘图,参考效果很好:

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

如何在后面显示剧情的同时还能参考?我知道我可以简单地将块移动到我希望情节出现的地方,但这对我来说并不理想。

在后面的chunk中使用ref.label,参考图中后面的chunk名称。

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

```