【发布时间】:2015-03-07 15:07:15
【问题描述】:
也许问题已被提出并解决,但解决方案对我不起作用。
我编写了一个能够创建 ggplot 对象并将它们以向量返回的函数。下面是函数内部的代码,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)))
}
我想要做的是使用上述函数返回一个串联列表P,其中包含几个 ggplots 对象,如下所示,这是“手动”版本工作正常:
p1 <- ggplot()+ ...
p2 <- ggplot()+ ...
p3 <- ggplot()+ ...
pdf('...')
grid.arrange(p1, p2, p3, nrow = 3)
dev.off()
返回num 的目的是为了以后在布局arg 中使用。 grid.arrange 函数。我有 PLOTS 作为返回变量:
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帮助我调试,谢谢!
【问题讨论】:
-
grid.arrange中的省略号需要 grobs。您要传递的任何其他参数都需要命名。例如,do.call(grid.arrange, c(P$plots, nrow = P$num))。 (作为评论发布,因为您没有提供可重现的测试示例。我不确定P$plots是否实际上是一个列表,它必须是这个列表才能工作。) -
抱歉回复晚了,我只是根据您的建议编辑了帖子,请检查一下。
do.call(grid.arrange, c(P$plots, nrow = P$num))也无法正常工作。
标签: r function vector ggplot2 parameter-passing