如何将 ggplot 对象的向量传递给 grid.arrange 函数?

How to pass a vector of ggplot objects to grid.arrange function?

也许问题已经提出并解决了,但解决方案对我不起作用。 我写了一个函数,能够创建 ggplot 对象并 return 它们在一个向量中。下面是函数内部的代码,vars是我的数据d.

的列名向量
plotting <- function(d){
    P <- numeric(0)
    vars <- names(d)[!names(d)%in%c('channel','label')]
    for (var in vars){
        p <- ggplot(d, aes(x=channel,y=var)) + 
             geom_boxplot(aes(fill=label)) + ggtitle(var)
        P <- c(P,p)
    }
    return(list(plots=P, num=length(vars)))
}

我想要做的是使用上面的函数 return 一个由几个 ggplots 对象组成的串联列表 P,如下所示,'manual' 版本工作正常:

p1 <- ggplot()+ ...
p2 <- ggplot()+ ...
p3 <- ggplot()+ ...
pdf('...')
grid.arrange(p1, p2, p3, nrow = 3)
dev.off()

returning num 的目的是为了稍后在布局 arg 中使用。 grid.arrange 函数。我有 PLOTS 作为 returning 变量:

PLOTS <- plotting(d)
pdf('...')
grid.arrange(PLOTS$plots, PLOTS$num)
dev.off()

我得到错误:

Error in arrangeGrob(..., as.table = as.table, clip = clip, main = main,  :
input must be grobs!

所以我尝试了Passing a vector to grid.arrange as a list of arguments.

中的解决方案
do.call(grid.arrange, c(PLOTS$plots, nrow = PLOTS$num))

但仍然出现同样的错误。 如有任何意见,我们将不胜感激。

编辑:使问题描述更清晰,并在下面粘贴可重现的数据d

structure(list(percent = c(0.0962463533974437, 0.129409967469436,
0.0150265653130588, 0.00299276735619027, 0.0108596845008112,
0.00407417010800106), songs = c(0.231617443342384, 0.430320945945946,
0.109264389042782, 0.282109656611649, 0.0288753799392097, 0.041635687732342
), label = c("1", "1", "1", "1", "1", "1"), channel = c("2",
"2", "2", "2", "2", "2")), .Names = c("percent", "songs", "label",
"channel"), row.names = c(NA, 6L), class = "data.frame")

请输入d作为plotting的参数,然后继续PLOTS$plots帮助我调试,谢谢!

您的绘图函数有一些问题。首先,您需要将 P 初始化为 list。其次,如果要使用 character 输入 var,则需要使用 aes_string 而不是 aes。然后你必须使用 list(p),以保持 ggplot 对象完整。

plotting <- function(d){
  P <- list()
  vars <- names(d)[!names(d)%in%c('channel','label')]
  for (var in vars){
    p <- ggplot(d, aes_string(x='channel', y=var)) + 
      geom_boxplot(aes(fill=label)) + ggtitle(var)
    P <- c(P, list(p))
  }
  return(list(plots=P, num=length(vars)))
}

PLOTS <- plotting(d)
do.call(grid.arrange, c(PLOTS$plots, nrow = PLOTS$num))