如何使用grid.arrange排列任意数量的ggplots?

93

这篇文章同时发布在 ggplot2 的 Google 群组上

我的情况是,我正在编写一个函数,该函数会输出任意数量的图表(取决于用户提供的输入数据)。该函数返回一个包含 n 个图表的列表,并且我想将这些图表以 2 x 2 的形式布局。我遇到了以下问题:

  1. 如何允许灵活处理任意数量(n)的图表?
  2. 如何指定它们应该按 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)

正如我所惯常的那样,我谦卑地蜷缩在角落里,热切地期待着比我更聪明的社区的睿智反馈。特别是如果我把这件事弄得比必要的还要难。


2
恭喜你提出了一个非常好的问题。我将把它作为撰写良好的 SO [r] 问题的示例。 - JD Long
1
特别是“谦卑地聚集”这部分——没有什么比好的卑躬屈膝更好了 :-) - Ben Bolker
@JD和@Ben - 你们的夸奖让我感到受宠若惊。真心地感谢你们的帮助。 - briandk
3个回答

45
你已经快要成功了!问题在于do.call期望你的参数是以命名的list对象形式提供的。你把它们放在了列表中,但是作为字符字符串而不是命名列表项。
我认为这应该可以解决:
args.list <- c(plot.list, 2,2)
names(args.list) <- c("x", "y", "z", "nrow", "ncol")

正如Ben和Joshua在评论中指出的那样,我可以在创建列表时分配名称:

args.list <- c(plot.list,list(nrow=2,ncol=2))
或者
args.list <- list(x=x, y=y, z=x, nrow=2, ncol=2)

1
我修改了代码好几次。对于这些修改我感到抱歉。现在它是否有意义?之前当我说它们是向量时,我说错了。对此我感到很抱歉。 - JD Long
2
你可以在创建列表时为参数命名:args.list <- list(x=x, y=y, z=x, nrow=2, ncol=2) - Joshua Ulrich
2
不完全是。你的长度是正确的。你的列表结构与JD的列表结构不同。使用str()和names()。你的所有列表元素都没有命名,因此为了使do.call成功,需要确切的位置匹配。 - IRTFM
2
@JD Long; 我完全同意。即使它不能防止所有错误,但如果您使用命名参数,仍然可以获得更好的错误消息和traceback()信息。 - IRTFM
1
我不太明白这里的讨论;因为grid.arrange()的第一个参数是...,所以位置匹配可能无关紧要。每个输入必须是网格对象(带有或不带有名称)、grid.layout的命名参数或其余参数的命名参数。 - baptiste
显示剩余5条评论

16

试试这个:

require(ggplot2)
require(gridExtra)
plots <- lapply(1:11, function(.x) qplot(1:10,rnorm(10), main=paste("plot",.x)))

params <- list(nrow=2, ncol=2)

n <- with(params, nrow*ncol)
## add one page if division is not complete
pages <- length(plots) %/% n + as.logical(length(plots) %% n)

groups <- split(seq_along(plots), 
  gl(pages, n, length(plots)))

pl <-
  lapply(names(groups), function(g)
         {
           do.call(arrangeGrob, c(plots[groups[[g]]], params, 
                                  list(main=paste("page", g, "of", pages))))
         })

class(pl) <- c("arrangelist", "ggplot", class(pl))
print.arrangelist = function(x, ...) lapply(x, function(.x) {
  if(dev.interactive()) dev.new() else grid.newpage()
   grid.draw(.x)
   }, ...)

## interactive use; open new devices
pl

## non-interactive use, multipage pdf
ggsave("multipage.pdf", pl)

3
在 gridExtra 版本大于等于0.9的情况下,如果 nrow*ncol < length(plots),则可以使用 marrangeGrob 自动完成所有这些操作。请注意,该函数不会改变原始内容,只会重新排列图形,并使其更易于管理。 - baptiste
5
ggsave("multipage.pdf", do.call(marrangeGrob, c(plots, list(nrow=2, ncol=2)))) - baptiste

4
我虽然有点晚了,但在R Graphics Cookbook中发现了一个解决方案,它使用一个名为multiplot的自定义函数,实现了非常类似的功能。也许这将帮助那些遇到这个问题的其他人。由于该解决方案可能比其他答案更新,因此我将其作为答案添加。
链接: 多图展示(ggplot2) 这是目前的函数,但请使用上面的链接,因为作者指出它已经更新为ggplot2 0.9.3,这意味着它可能会再次更改。
# Multiple plot function
#
# ggplot objects can be passed in ..., or to plotlist (as a list of ggplot objects)
# - cols:   Number of columns in layout
# - layout: A matrix specifying the layout. If present, 'cols' is ignored.
#
# If the layout is something like matrix(c(1,2,3,3), nrow=2, byrow=TRUE),
# then plot 1 will go in the upper left, 2 will go in the upper right, and
# 3 will go all the way across the bottom.
#
multiplot <- function(..., plotlist=NULL, file, cols=1, layout=NULL) {
  require(grid)

  # Make a list from the ... arguments and plotlist
  plots <- c(list(...), plotlist)

  numPlots = length(plots)

  # If layout is NULL, then use 'cols' to determine layout
  if (is.null(layout)) {
    # Make the panel
    # ncol: Number of columns of plots
    # nrow: Number of rows needed, calculated from # of cols
    layout <- matrix(seq(1, cols * ceiling(numPlots/cols)),
                    ncol = cols, nrow = ceiling(numPlots/cols))
  }

 if (numPlots==1) {
    print(plots[[1]])

  } else {
    # Set up the page
    grid.newpage()
    pushViewport(viewport(layout = grid.layout(nrow(layout), ncol(layout))))

    # Make each plot, in the correct location
    for (i in 1:numPlots) {
      # Get the i,j matrix positions of the regions that contain this subplot
      matchidx <- as.data.frame(which(layout == i, arr.ind = TRUE))

      print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row,
                                      layout.pos.col = matchidx$col))
    }
  }
}

创建绘图对象:

p1 <- ggplot(...)
p2 <- ggplot(...)
# etc.

然后将它们传递给 multiplot

multiplot(p1, p2, ..., cols = n)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接