繁体   English   中英

如何在 R 中的两列中打印大量 ggplot 图形而不将它们展平?

[英]How can I make a large number of ggplot figures print in two columns in R without flattening them?

例如,如果您运行以下命令,您将看到 grid.arrange 将所有 20 个 ggplot 图压缩成一个图形,使它们无法读取。

有没有办法创建一个可以包含几十个这样的图的高大数字,或者有没有一种简单的方法让它们通过 grid.arrange 输出一次 2 x 2 打印四个,直到列表中没有更多?

列表中的数字可能被四整除,也可能不能被四整除。 例如,如果我在列表中有 9 个图,它需要打印一个 2 x 2 的图像,另一个 2 x 2 的图像,然后是最后一个。

library(gridExtra)
library(ggplot2)

#Create the dataframe.
df<-data.frame(matrix(rexp(200), 10))
colnames(df)<-c("aa", "bb", "cc", "dd", "ee", "ff", "gg", "hh", "ii", "jj", "aa", "bb", "cc", "dd", "ee", "ff", "gg", "hh", "ii", "jj")

#Create the ggplots in a loop.
hlist<-list()
for(i in 1:ncol(df)){
  
  hplot<-eval(substitute(ggplot(df[i], aes(x=df[,i])) + geom_histogram(),list(i = i)))
  
  hlist[[i]]<-hplot
}

#Print the plots.
grid.arrange(grobs = hlist, ncol = 2)

在将所有绘图存储在新列表中后,尝试使用patchwork创建一个 2x2 绘图创建索引的方法。 使用索引向量,您可以设置一个循环并使用wrap_plots()来排列它们。 这里的代码:

library(ggplot2)
library(patchwork)

#Create the dataframe.
df<-data.frame(matrix(rexp(200), 10))
colnames(df)<-c("aa", "bb", "cc", "dd", "ee", "ff", "gg", "hh", "ii", "jj", "aa", "bb", "cc", "dd", "ee", "ff", "gg", "hh", "ii", "jj")

#Create the ggplots in a loop.
hlist<-list()
for(i in 1:ncol(df)){
  
  hplot<-eval(substitute(ggplot(df[i], aes(x=df[,i])) + geom_histogram(),list(i = i)))
  
  hlist[[i]]<-hplot
}
#Print the plots.
vec <- seq(1,length(hlist),by=4)
vec2 <- seq(4,length(hlist),by=4)
#New list
hlist2 <- list()
#Loop
for(i in 1:length(vec))
{
  hlist2[[i]] <- wrap_plots(hlist[vec[i]:vec2[i]],ncol = 2)
}
#Arrange
finalplot <- wrap_plots(hlist2,ncol = 2)

输出:

在此处输入图片说明

所有 2x2 图都存储在hlist2

我找到了创建绘图页面列表然后使用 marrangeGrob 打印每个页面的解决方案:

library(gridExtra)
library(ggplot2)

#Create the dataframe.
df<-data.frame(matrix(rexp(200), 10))
colnames(df)<-c("aa", "bb", "cc", "dd", "ee", "ff", "gg", "hh", "ii", "jj", "aa", "bb", "cc", "dd", "ee", "ff", "gg", "hh", "ii", "jj")

#Create the ggplots in a loop.
hlist<-list()
for(i in 1:ncol(df)){
  
  hplot<-eval(substitute(ggplot(df[i], aes(x=df[,i])) + geom_histogram(),list(i = i)))
  
  hlist[[i]]<-hplot
}

#Uses marrangeGrob to first store them in multiple pages.
glist<-marrangeGrob(hlist, nrow=2, ncol=2)

#Print each page one at a time until through all pages.
for(i in 1:length(glist)){grid.arrange(grobs = glist[i], ncol = 1)}

暂无
暂无

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

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