当保存在 r 中的矩阵中时,在网格中显示保存的 ggplots

Displaying saved ggplots in a grid when saved in a matrix in r

我使用循环创建了绘图并将它们保存在矩阵中 ()。我现在想使用 plot_grid 或类似的方法在网格中排列图。有没有一种简单的方法来调用已保存地块的矩阵?我希望生成的绘图网格与矩阵的布局相匹配。

library(ggplot2)
library(gridExtra)
library(cowplot)


# create and save the plots to the matrix
plt <- vector('list', 10)
plt <- matrix(plt, nrow = 5, ncol = 2)

it = 1
while (it < 5){
  myX = runif(10)
  myY = runif(10)
  df = data.frame(myX,myY)
  plt[[it, 1]] = ggplot(data = df, aes(myX, myY)) + 
    geom_point(size = 2, color = "blue")
  plt[[it, 2]] = ggplot(data = df, aes(myX, myY)) + 
    geom_point(size = 2, color = "red")
  it = it + 1
}  

# display the plots in a grid that matches the matrix format
a1<- plt[[1,1]]
b1 <-plt[[1,2]]

a2<- plt[[2,1]]
b2 <-plt[[2,2]]

plot_grid(a1, b1, a2, b2, ncol = 2)

我上面的方法有效,但我不得不将矩阵的每个元素分配给一个变量,然后在 plot_grid 命令中按顺序手动调用所有变量。我正试图找到一种方法来避免这种情况。我刚刚在这里展示了一个 4 的网格 - 我的实际问题中有更多的图。

我试过使用 plot_grid(plt, ncol = 2),它给出了错误“无法将 class 矩阵数组的对象转换为 grob。”我也试过 mylist = c(plt[[1,1]], plt[[1,2]], plt[[2,1]], plt[[2,2]])plot_grid(mylist, ncol = 2) 但得到了同样的错误。

我也尝试使用基于 this answerdo.call("grid.arrange", c(plt, ncol = 2)) 但无法正常工作。

在矩阵中存储非原子对象可能会非常混乱。所以首先,在一个普通列表中收集你想要的地块,然后,当将列表传递给 plot_grid 时,一定要通过 plotlist= 参数

这样做
mylist = list(plt[[1,1]], plt[[1,2]], plt[[2,1]], plt[[2,2]])
plot_grid(plotlist=mylist, ncol=2)

如果您想绘制所有值,那么您只需要转置列表,因为列表按列顺序存储,但默认情况下按行顺序绘制

plot_grid(plotlist=t(plt), ncol=2)

如果您有一个普通列表而不是矩阵列表,do.call 会起作用。你可以有一个辅助函数来在尝试绘图时从列表中删除矩阵部分。例如

undim <- function(x) {dim(x) <- NULL; x}
do.call("plot_grid", c(undim(plt), ncol = 2))

不过这里的plotlist=参数绝对是dg比较好的方法

与@MrFlick 一致,我建议将您的绘图存储在一个列表中,该列表可以通过参数 plotlist

轻松传递给 plot_grid
library(ggplot2)
library(gridExtra)
library(cowplot)

it = 1
plt <- list()
while (it < 5){
  myX = runif(10)
  myY = runif(10)
  df = data.frame(myX,myY)
  p1 <- ggplot(data = df, aes(myX, myY)) + 
    geom_point(size = 2, color = "blue")
  p2 <- ggplot(data = df, aes(myX, myY)) + 
    geom_point(size = 2, color = "red")
  
  plt <- c(plt, list(p1, p2))
  it <- it + 1
}  

# display the plots in a grid that matches the matrix format
plot_grid(plotlist = plt, ncol = 2)