将 ggplot 对象的列表转换为 grobs 的列表,以便 grid.arrange 可以接受?

5

我正在遍历某些数据,创建ggplot图形的列表,并希望将其打印到单个图像上。我的代码有两个循环,一个内嵌在另一个中。外部循环根据一个变量将数据细分。内部循环进一步细分数据并为每个细分产生散点图;这些图形保存在一个列表中。内部循环完成后,使用类似于此处的列表对象创建了一个grid.arrange对象(注:此代码包括在本问题底部共享的自定义函数my_scatter):

require(ggplot2)
require(grid)
require(gridExtra)
PRIMARY LOOP STRUCTURE {
    ...
    my_plots = list()
      for (j in c(1:length(my_nodes))){
        cur_node = my_nodes[j]
        node_dat = temp_dat[temp_dat$Node == cur_node,]
        p = my_scatter(node_dat, "PRE", "POST") + geom_point(aes(color = Node, shape = Recurrence_Type, size = 2))
        my_plots[[j]] = p
      }         
    grid.arrange(my_plots[[1]],my_plots[[2]],my_plots[[3]],my_plots[[4]],my_plots[[5]], nrow = 4, ncol = 3)
}

问题在于循环的某些迭代中,my_plots 的元素数量会有所不同。我知道可以通过一系列条件语句来解决这个问题:
if (length(my_plots) == 2) {
    grid.arrange(my_plots[[1]],my_plots[[2]],nrow=1,ncol=2)
} elsif ( length(my_plots == 3) {
    grid.arrange(my_plots[[1]],my_plots[[2]],nrow=2,ncol=2)
} elsif...

但这种方法似乎很繁琐,我希望找到一种不那么生硬的解决方案。通常情况下,我会使用facet_grid()来完成这种事情,但当它需要生成超过2或3个图形时,facet_grid生成的超薄长方形散点图很难解释。
我看到这个问题似乎使用grobslapply解决了这个问题——这是R编程中我过去从未成功过的两个方面。
我该如何做到以下两点之一:
  • 将我的ggplot对象列表更改为grid.arrange可接受的grobs列表?
  • 告诉facet_grid(或类似的现有函数),我想要多行图形以便它们接近方形形状?
这是第一个代码块中使用的my_scatter函数:
my_scatter = function (df,a,b) {
  test1 = class(df)
  if (! test1 == "data.frame") { 
    stop("1st Variable should be a data frame")
  }
  test2 = class(df[,a])
  valid_classes = c("integer", "numeric")
  if (! test2 %in% valid_classes) {
    stop("2nd Variable should either be an integer or numeric")
  }
  test3 = class(df[,b])
  if (! test3 %in% valid_classes) {
    stop("3rd Variable should either have class numeric or integer")
  }
  p = ggplot(data = df, aes_string(a, b)) + xlim(0,1) + ylim(0,1) + geom_point() + geom_abline(slope = 1, intercept = 0, color = "white")
  return(p)
} 

顺便提一下你的第二个子问题,可以检查 facet_wrapnrow/ncol 参数。 - baptiste
1
顺便提一句,检查类的更简洁的方法是 stopifnot(inherits(df, "data.frame")) - baptiste
1个回答

12
grid.arrange(grobs = my_plots)

这应该能解决问题。您不需要将图形转换为grobs,grid.arrange会为您完成。但是如果必要,您可以执行以下操作:

my_grobs = lapply(my_plots, ggplotGrob)

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