user3138373
user3138373

Reputation: 523

plotting every graph on separate page in the pdf output file using ggplot

I am trying to use lapply to plot 3 graphs using ggplot package for every file I am looping through.

Here is my code:

pdf("outfile.pdf")
lapply(files,function(x){
  a <- basename(x)
  a <- gsub("*_junc_with_type_genename_fpkm.txt","",a)
  d <- fread(x,drop=c(1:4,6,7))
  setnames(d, c("junc_counts", "TYPE","gene_name","sgd_name","fpkm"))

  p1 <- ggplot(...)
  p2 <- ggplot(...)
  p3 <- ggplot(...)
  grid.arrange(p1,p2,p3)
})
dev.off()

So if there are 5 input files, I want to plot 15 graphs(3 for each file: p1,p2,p3) on separate pages in the pdf output file.

Right now 3 graphs on one page are being plotted by the above code.

Upvotes: 2

Views: 196

Answers (1)

Romain
Romain

Reputation: 2151

The grid.arrange() statement wraps the three plots into a single plot, that is why you get 3 plots per page. Probably not the prettiest solution, but you might use another loop so that one page is printed for each graph :

library(ggplot2)

pdf("outfile.pdf")
lapply(1:5,function(x){
  p1 <- ggplot(cars, aes(dist, speed)) + geom_point()
  p2 <- ggplot(cars, aes(dist, speed)) + geom_path()
  p3 <- ggplot(cars, aes(speed, dist)) + geom_point(color='blue')

  # this loop so that pdf device creates a new page for each plot
  lapply(list(p1, p2, p3), function(plot) plot)
})
dev.off()

Upvotes: 2

Related Questions