marrangeGrob 后不能使用 ggsave

cannot use ggsave after marrangeGrob

我正在使用以下设置创建 个图表列表。

效果很好:

library(grid)
library(gridExtra)
library(ggplot2)

mycols <- c('year','displ')

mylist <- list()
for(item in mycols){

  p <- ggplot(mpg, aes_string(x = 'hwy', y = item)) +  
    geom_point()
  mylist[[(length(mylist) +1)]] <- p
}

ml = marrangeGrob(grob = mylist, nrow=2, ncol=1)
ggsave("P://multipage.pdf", ml, width =10, height = 5)

但是,在循环中,替换:

Error in $<-.data.frame(*tmp*, "wrapvp", value = list(x = 0.5, y = 0.5, : replacement has 17 rows, data has 234

这里有什么问题?单独来看,列表中的所有图表看起来都不错。

谢谢!

这确实与 marrangeGrob 无关,而与您构建列表的方式有关。比较这些方法输出的结构

out1 <- list()
out1[[length(out1)+1]]<-list(a=1, b=2)
out1[[length(out1)+1]]<-list(a=2, b=2)
str(out1)
# List of 2
#  $ :List of 2
#   ..$ a: num 1
#   ..$ b: num 2
#  $ :List of 2
#   ..$ a: num 2
#   ..$ b: num 2

out2 <- list()
out2 <- append(out2, list(a=1, b=2))
out2 <- append(out2, list(a=2, b=2))
str(out2)
# List of 4
#  $ a: num 1
#  $ b: num 2
#  $ a: num 2
#  $ b: num 2

注意它们产生不同的结构。 append() 将元素添加到 "root" 列表中,而不是将列表嵌套在列表中。您可以自己明确地使用和额外的 list()

out3 <- list()
out3 <- append(out3, list(list(a=1, b=2)))
out3 <- append(out3, list(list(a=2, b=2)))
str(out3)
# List of 2
#  $ :List of 2
#   ..$ a: num 1
#   ..$ b: num 2
#  $ :List of 2
#   ..$ a: num 2
#   ..$ b: num 2

但很少需要像这样在 R 中搞乱循环。最好使用内置迭代器,如 lapply()Map()。例如

mylist <- lapply(mycols, function(item) {
  ggplot(mpg, aes_string(x = 'hwy', y = item)) + 
    geom_point()
})