简体   繁体   English

如何创建 grid.arrange 将接受并在 r 中绘制的 ggplot 对象列表

[英]How to create a list of ggplot objects that grid.arrange will accept and draw in r

Update The below code runs now after kernel restart.更新kernel 重新启动后,下面的代码现在运行。 I'm leaving the question since I didn't see this exact method of converting the plot object into a list and appending.我留下了这个问题,因为我没有看到将 plot object 转换为列表并附加的确切方法。

I want to dynamically create a list of ggplot2::ggplot objects (gg) and pass that list to gridExtra::grid.arrange() to draw them.我想动态创建一个 ggplot2::ggplot 对象(gg)列表并将该列表传递给 gridExtra::grid.arrange() 以绘制它们。

However, I'm getting errors when I try (see bottom of code below).但是,我在尝试时遇到错误(请参阅下面的代码底部)。

How do I create a list of ggplots and use it in grid.arrange() (or anywhere I want one or more gg objects or grobs)?如何创建 ggplots 列表并在 grid.arrange() (或我想要一个或多个 gg 对象或 grobs 的任何地方)中使用它?

I've looked at these posts , but the solutions didn't work.我看过这些帖子,但解决方案不起作用。

Here's a simple example with outputs:这是一个带有输出的简单示例:

# RStudio Version 1.3.1093
# R version 4.0.3 (2020-10-10)
# ggplot2 version 3.3.2
# gridExtra version 2.3

library(ggplot2)
library(gridExtra)

test_fun = function (x) {
  plt_lst = list()
  
  for(col in colnames(x)){
    plt = ggplot(data = x, aes(x = x[ , col])) +
      geom_histogram()
    plt_lst = append(plt_lst, list(plt))
    grid.arrange(plt) # Draws each graph.
    print(is(plt))
    # [1] "gg"
    print(is(plt[[1]]))
    # [1] "data.frame" "list"       "oldClass"   "vector"
  }
  
  return(plt_lst)
}

df = data.frame(a = rnorm(n = 50),
                b = rnorm(n = 50))

test_plt_lst = test_fun(df)
print(is(test_plt_lst))
# [1] "gg"
print(is(test_plt_lst[[1]]))
# [1] "data.frame" "list"       "oldClass"   "vector"

# grid.arrange(test_plt_lst)
# # Error in gList(list(data = list(a = c(1.14459276559037, 2.33485713757935, : only 'grobs' allowed in "gList"


# Works
do.call(grid.arrange, test_plt_lst)
# The following error no longer appearing.
# Error in `$<-.data.frame`(`*tmp*`, "wrapvp", value = list(x = 0.5, y = 0.5, : replacement has 17 rows, data has 50

You can try to:您可以尝试:

  1. Initialise the length of the list because growing objects in a loop is considerably slow.初始化列表的长度,因为循环中增长的对象非常慢。
  2. Use .data pronoun to subset the names so you get proper names on x-axis.使用.data代词对名称进行子集化,以便在 x 轴上获得专有名称。
library(ggplot2)
library(gridExtra)

test_fun = function (x) {
  plt_lst = vector('list', length(x))
  nm <- names(x)

  for(i in seq_along(x)){
    plt_lst[[i]] = ggplot(data = x, aes(x = .data[[nm[i]]])) + geom_histogram()
  }
  
  return(plt_lst)
}


test_plt_lst = test_fun(df)
do.call(grid.arrange, test_plt_lst)

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM