我认为您想创建由 ggplot2 创建的一堆图的网格布局。不幸的是,par(mfrow=)
这是一个不适用于 ggplot2 的基本图形功能。grid.arrange
在 gridExtra 包中使用。
library(ggplot2)
library(gridExtra)
# Completely fake plotting function.
makePlot = function(a, b) {
dat = data.frame(x=rnorm(a), y=rnorm(a))
p = ggplot(dat, aes(x=x, y=y)) +
geom_point(size=b, alpha=1/b) +
opts(title=paste("a = ", a, ", b = ", b, sep="")) +
opts(plot.title=theme_text(size=12))
return(p)
}
plot_list = list() # Create an empty list to hold plots.
for (b in c(1, 3, 6)) { # I switched a and b loops
for (a in seq(100, 900, by=100)) { # to make the final layout neater.
p = makePlot(a, b)
plot_list = c(plot_list, list(p)) # Add new plot to list.
}
}
pdf("mytry1.pdf", width = 14, height = 6)
do.call(grid.arrange, c(plot_list, list(nrow=3, ncol=9, main="Grid of Plots")))
dev.off()
编辑:这可以更简洁吗?
plot_list
可以更紧凑地创建并输出为 pdf 。感谢@baptiste 的建议mlply
,ggsave
和arrangeGrob
。
library(plyr)
plot_list = mlply(expand.grid(a=seq(100, 900, by=100), b=c(1, 3, 6)), makePlot)
ggsave(filename="grid_1.pdf", height=6, width=14,
plot=do.call(arrangeGrob, c(plot_list, nrow=3, main="Grid of Plots")))