【发布时间】:2011-07-13 15:10:44
【问题描述】:
这是在 ggplot2 谷歌组中交叉发布的
我的情况是我working on a function 输出任意数量的图(取决于用户提供的输入数据)。该函数返回 n 个图的列表,我想将这些图以 2 x 2 的形式排列。我正在努力解决以下同时出现的问题:
- 如何灵活处理任意 (n) 个地块?
- 如何指定我希望它们以 2 x 2 的形式布置
我当前的策略使用来自gridExtra 包的grid.arrange。这可能不是最佳的,尤其是因为这是关键,它完全不起作用。这是我注释的示例代码,尝试了三个图:
library(ggplot2)
library(gridExtra)
x <- qplot(mpg, disp, data = mtcars)
y <- qplot(hp, wt, data = mtcars)
z <- qplot(qsec, wt, data = mtcars)
# A normal, plain-jane call to grid.arrange is fine for displaying all my plots
grid.arrange(x, y, z)
# But, for my purposes, I need a 2 x 2 layout. So the command below works acceptably.
grid.arrange(x, y, z, nrow = 2, ncol = 2)
# The problem is that the function I'm developing outputs a LIST of an arbitrary
# number plots, and I'd like to be able to plot every plot in the list on a 2 x 2
# laid-out page. I can at least plot a list of plots by constructing a do.call()
# expression, below. (Note: it totally even surprises me that this do.call expression
# DOES work. I'm astounded.)
plot.list <- list(x, y, z)
do.call(grid.arrange, plot.list)
# But now I need 2 x 2 pages. No problem, right? Since do.call() is taking a list of
# arguments, I'll just add my grid.layout arguments to the list. Since grid.arrange is
# supposed to pass layout arguments along to grid.layout anyway, this should work.
args.list <- c(plot.list, "nrow = 2", "ncol = 2")
# Except that the line below is going to fail, producing an "input must be grobs!"
# error
do.call(grid.arrange, args.list)
按照我的习惯,我谦虚地蜷缩在角落里,热切地等待一个比我聪明得多的社区的明智反馈。尤其是如果我让这变得比需要的更难的话。
【问题讨论】:
-
对一个非常出色的问题表示敬意。我将以此为例说明如何编写一个好的 SO [r] 问题。
-
尤其是“谦逊地挤在一起”的部分——没有什么比得上一个好卑鄙的人了 :-)
-
@JD 和@Ben - 我很受宠若惊,伙计们。真挚地。我非常感谢您的帮助。