handle multiple plot with ggplot R

2020-04-23 07:44发布

问题:

I have a big data frame and I'm using ggplot.

ggplot()+
  geom_line(data=DATA,aes(logl,PercPos,group=name),col="blue")+
  geom_line(data=DATA,aes(logl,PercNeg,group=name),col="green")+ 
  geom_histogram(data=DATA, aes(x=logl,alpha=.5,group=name),bindwidth=0.1,density=T)+
  facet_wrap(~ name,as.table=T)+
  theme_bw()+
  xlim(min(DATA$logl),max(DATA$logl))

It generates 180 different plot. I would like to have the results plotted in different file , for example not more than 30 plot in each file.

Is there an easy automatic way to do that?

Thanks for help.

回答1:

Here's one approach:

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()

You can also use marrangeGrob from gridExtra, in which case no facetting is needed:

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)


标签: r ggplot2