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

更新 下面的代码在内核重启后运行。我要离开这个问题,因为我没有看到这种将绘图对象转换为列表并附加的确切方法。

我想动态创建一个 ggplot2::ggplot 对象 (gg) 列表并将该列表传递给 gridExtra::grid.arrange() 以绘制它们。

但是,我在尝试时遇到错误(请参阅下面的代码底部)。

如何创建 ggplots 列表并在 grid.arrange()(或我想要一个或多个 gg 对象或 grobs 的任何地方)中使用它?

我查看了 these posts,但解决方案不起作用。

这是一个带有输出的简单示例:

# 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
yqf1996 回答:如何创建 grid.arrange 将接受并在 r 中绘制的 ggplot 对象列表

你可以试试:

  1. 初始化列表的长度,因为循环中的对象增长速度相当慢。
  2. 使用 .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)

enter image description here

本文链接:https://www.f2er.com/1149864.html

大家都在问