使用ggplot在一页上绘制多个图 [英] Multiple plots on one page using ggplot
问题描述
我有12个通过循环生成的图,我想在一页上用3行2列来绘制它们(总共2页).我知道如何用R
I have 12 plots generated by a loop and I want to plot them with 3 rows and 2 columns on one page (2 pages in total). I know how to do it in R
pdf("1.pdf")
par(mfrow = c(3, 2))
for (i in 1:12) {
x <- 1:10
y <- 2*x + rnorm(x)
plot(x, y)
}
dev.off()
但是如何使用ggplot
执行此操作?
But how to do this using ggplot
?
library(ggplot2)
library(grid)
library(gridExtra)
for (i in 1:12) {
x <- 1:10
y <- 2*x + rnorm(x)
qplot(x, y)
}
我认为我必须使用grid.arrange
,但是在这方面需要一些帮助.谢谢.
I think I have to use grid.arrange
but need some help on that. Thanks.
推荐答案
您可能想看看cowplot
软件包,该软件包比仅仅使用裸露的grid.arrange
还具有更大的灵活性.
You might want to take a look at the cowplot
package that allows more flexibility than just using a naked grid.arrange
.
这行得通-尽管有点过分:
This works - albeit a bit inelegantly:
library(ggplot2)
library(grid)
library(gridExtra)
lg <- list()
for (i in 1:12) {
x <- 1:10
y <- 2*x + rnorm(x)
lg[[i]] <- qplot(x, y)
}
grid.arrange(lg[[1]],lg[[2]],lg[[3]],lg[[4]],lg[[5]],lg[[6]],nrow=3,ncol=2)
grid.arrange(lg[[7]],lg[[8]],lg[[9]],lg[[10]],lg[[11]],lg[[12]],nrow=3,ncol=2)
以下是另一种更优雅但有些晦涩的方式来完成grid.arrange
(感谢Axeman和甜菜根-注意注释).
Another more elegant but somewhat obtuse way to do the grid.arrange
is the following (thanks to Axeman and beetroot - note the comments).
do.call(grid.arrange, c(lg[1:6], nrow = 3))
do.call(grid.arrange, c(lg[7:12], nrow = 3))
或者这个:
grid.arrange(grobs = lg[1:6], ncol=2)
grid.arrange(grobs = lg[7:12], ncol=2)
它们都导致以下结果-(想想其中的两个-无论如何它们看起来都一样):
They all result in this - (think two of these - they look the same anyway):
这篇关于使用ggplot在一页上绘制多个图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!