【问题标题】:Looping through a list of ggplots and giving each a figure caption using Knitr循环遍历 ggplots 列表并使用 Knitr 给每个图形标题
【发布时间】:2018-10-12 23:04:14
【问题描述】:

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

【问题讨论】:

  • 作为 R Markdown 提示,您可以在第一个代码块中使用 include=FALSE 参数来抑制任何输出。这意味着您不必将所有函数都包装在 SupressStartupMessages(): yihui.name/knitr/options/#code-evaluation 中。希望有帮助:)

标签: r ggplot2 r-markdown knitr pandoc


【解决方案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') 
}

``` 

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

【讨论】:

    猜你喜欢
    • 2017-01-24
    • 1970-01-01
    • 2013-06-11
    • 1970-01-01
    • 1970-01-01
    • 2011-03-09
    • 1970-01-01
    • 2023-03-25
    • 2016-07-19
    相关资源
    最近更新 更多