2

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.

0

1 Answer 1

2

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.