我使用循环创建了图并将它们保存在矩阵中(请参阅我之前的问题)。我现在想使用 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)
,它给出了错误“无法将类矩阵数组的对象转换为 grob”。我也尝试过mylist = c(plt[[1,1]], plt[[1,2]], plt[[2,1]], plt[[2,2]])
,plot_grid(mylist, ncol = 2)
但得到了同样的错误。
我也尝试do.call("grid.arrange", c(plt, ncol = 2))
根据这个答案使用,但无法正常工作。