这是一种方法:
library(ggplot2)
library(plyr)
# dummy data with 181 different levels
N <- 181
d <- data.frame(x=rnorm(10*N), y=rnorm(10*N), f=gl(N, 10))
# group levels to fit ppp plots per page
split_df_ppp <- function(d, f, id.var = ".page_split", ppp=30){
stopifnot(is.factor(f))
n <- length(levels(f))
pages <- n%/%ppp + as.logical(n%%ppp)
groups <- split(levels(f), gl(pages, ppp, n))
d[[id.var]] <- f
levels(d[[id.var]]) <- groups
invisible(d)
}
d2 <- split_df_ppp(d, d$f)
str(d2)
# ggsave() could go in this function, if multiple files are preferred
plot_one_page <- function(.d){
qplot(x, y, data=.d) +facet_wrap(~f)
}
# here saving all plots as separate pages in one file
pdf("multipage.pdf")
# loop through pages
d_ply(d2, ".page_split", plot_one_page, .print=TRUE)
dev.off()
您也可以使用marrangeGrob
来自 gridExtra,在这种情况下不需要刻面:
lp = dlply(d, "f", function(d) qplot(x, y, data=d))
g = do.call(gridExtra::marrangeGrob, c(lp, ncol=5, nrow=6))
ggsave("multipage.pdf", g)