循环遍历 ggplots 列表并使用 Knitr 为每个图形标题

Looping through a list of ggplots and giving each a figure caption using Knitr

我正在使用 ggplot2 创建一系列绘图。其中每一个都是以编程方式命名的,我想使用这些名称为每个人提供自己的图形标题。我想从列表中提取名称并将它们动态传递给 fig.cap。

有办法吗?这是一个 MCVE,您可以在列表和各个图之间切换以查看数字消失或显示:

---
output: pdf_document
---

```{r, include = FALSE}
library(ggplot2)
library(knitr)
opts_chunk$set(echo=FALSE)
```

```{r}
## Plot 1
listOfPlots <- list(
  # Plot 1
  ggplot(data = diamonds) +
    geom_point(aes(carat, price)),

  ## Plot 2
  ggplot(data = diamonds) +
    geom_point(aes(carat, depth))
)

names(listOfPlots) <- c("This is caption 1", "This is caption 2")
```


```{r, fig.cap = c("This is caption 1", "This is caption 2"), echo=TRUE}

listOfPlots

# listOfPlots$`This is caption 1`
# listOfPlots$`This is caption 2`
```

备注:

如果要为其提供自己的标题,R Markdown 中的绘图之间需要有空格。如Yihui on your link所述,这里的技巧是在两张图片之间添加一些换行符。

```{r, fig.cap=c("Caption 1", "Caption 2")} 
listOfPlots[[1]]
cat('\n\n') 
listOfPlots[[2]]
``` 

注意,the double square brackets 仅用于 return 情节本身。

使用循环

假设您正在寻找一种适用于任何长度列表的更通用的方法,我们可以使用循环自动创建绘图之间的换行符。请注意 header:

块中需要 results="asis"
```{r, fig.cap=c("Caption 1", "Caption 2"), echo=FALSE, results="asis"} 

for(plots in listOfPlots){
  print(plots)
  cat('\n\n') 
}

``` 

作为最后的提示,您可能希望直接在标题中使用列表的名称。语法 {r, fig.cap = names(listOfPlots)} 可以实现这一点。