循环浏览ggplots列表,并使用Knitr给每个图一个标题

时间:2018-10-12 23:04:14

标签: r ggplot2 r-markdown knitr pandoc

我正在使用 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`
```

注释:

  • Yihui和其他人说过(https://groups.google.com/forum/#!topic/knitr/MJVLiVyGCro),要在一个块中包含多个图形并给它们提供图形标题,您需要具有echo = TRUE,因为内嵌图形和pandoc内容。
  • 我不想显示代码,数字的数量可能是可变的,所以我不想对事情进行硬编码。有趣的是,即使echo = TRUE,使用ggplots列表也不起作用。我必须分别调用每个ggplot。

1 个答案:

答案 0 :(得分:1)

如果要给它们自己的标题,则在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仅用于返回图本身。

使用循环

假设您正在寻找一种更通用的方法,该方法适用于任何长度的列表,我们可以使用循环自动在绘图之间创建换行符。请注意,块头中需要results="asis"

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

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

``` 

enter image description here

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