如何在 R Markdown 的列表中打印所有记录的图

How to print all recorded plots in a list in R Markdown

这是我在 Whosebug 上的第一个问题。如果我做错了什么,请告诉我以改进下一个问题。

我开始使用 R Markdown,但在使用 for 循环打印记录的绘图时遇到了一些麻烦。好吧,在我 运行 Rmarkdown 文件之前,我 运行 R 函数生成了几个数据帧和图表的列表。

为了方便起见,我在这里放了一个简化的可重现示例,该列表仅包含绘图对象。

x <- c(1,2,3,4,5)
y <- c(1,2,3,4,5)


plot(x,y)
abline(h=1)
p1.1 <- recordPlot()

plot(x,y)
abline(h=3)
p1.2 <- recordPlot()

plot(x,y)
abline(h=4)
p2.1 <- recordPlot()

plot(x,y)
abline(h=6)
p2.2 <- recordPlot()

lista<-NULL
lista["p1.1"] <- list(p1.1)
lista["p1.2"] <- list(p1.2)
lista["p2.1"] <- list(p2.1)
lista["p2.2"] <- list(p2.2)

save(new_list, file = "Data.RData")

然后我将此列表加载到 R Markdown 文件中,如下所示:

```{r setup}
knitr::opts_chunk$set(echo = TRUE,fig.keep = "all")
load("Data.RData")```

我试着像这样打印这个图:

```{r,echo=FALSE, results='asis',fig.keep='all'}
for (i in c(1,2)){
 for(j in c(1,2)){
  print(lista[[paste(paste("p",i,sep=""),j,sep=".")]])
 }
}```

当我 运行 Knitr 获取 HTML 文件时,结果是只显示了 for 循环的最后一个图。

我试过使用 lapply 而不是 for 循环,但它对我不起作用。我还尝试使用 replayPlot 函数 print(replayPlot(lista[[paste(paste(paste("p",i,sep=""),".",sep=""),j,sep="")]])) 得到相同的结果。

有没有办法在不修改之前生成绘图列表的 R 函数的情况下解决这个问题?

感谢您的回答。

您使用的语法可能适用于 ggplot 个对象的列表,但对于基础 plot 个对象,您需要调用 plot.new() 以便下一个绘图列表不会覆盖前一个:

---
title: "test"
output: html_document
---

## Define plots

```{r}
x <- c(1,2,3,4,5)
y <- c(1,2,3,4,5)

plot.new()
plot(x,y)
abline(h=1)
p1.1 <- recordPlot()

plot.new()
plot(x,y)
abline(h=3)
p1.2 <- recordPlot()

plot.new()
plot(x,y)
abline(h=4)
p2.1 <- recordPlot()

plot.new()
plot(x,y)
abline(h=6)
p2.2 <- recordPlot()

lista<-NULL
lista["p1.1"] <- list(p1.1)
lista["p1.2"] <- list(p1.2)
lista["p2.1"] <- list(p2.1)
lista["p2.2"] <- list(p2.2)

```

# Print list

```{r,echo=F}
for (i in c(1,2)){
 for(j in c(1,2)){
  # Needed to avoid overwrite
  plot.new()
  print(lista[[paste(paste("p",i,sep=""),j,sep=".")]])
 }
}
```

请注意,您可以简化循环的语法:

for(p in lista) {
  plot.new()
  print(p)
}