简体   繁体   English

用ggplot R处理多个图

[英]handle multiple plot with ggplot R

I have a big data frame and I'm using ggplot. 我有一个大数据框,正在使用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. 它生成180个不同的情节。 I would like to have the results plotted in different file , for example not more than 30 plot in each file. 我想将结果绘制在不同的文件中,例如每个文件中的绘图不超过30个。

Is there an easy automatic way to do that? 有没有简单的自动方法可以做到这一点?

Thanks for help. 感谢帮助。

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: 您还可以使用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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM