handle multiple plot with ggplot R

前端 未结 1 1024
旧时难觅i
旧时难觅i 2021-01-23 19:56

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         


        
1条回答
  •  鱼传尺愫
    2021-01-23 20:30

    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)
    

    0 讨论(0)
提交回复
热议问题