这篇文章同时发布在 ggplot2 的 Google 群组上
我的情况是,我正在编写一个函数,该函数会输出任意数量的图表(取决于用户提供的输入数据)。该函数返回一个包含 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)
正如我所惯常的那样,我谦卑地蜷缩在角落里,热切地期待着比我更聪明的社区的睿智反馈。特别是如果我把这件事弄得比必要的还要难。