Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Save multiple plots from a file list into a single file (png or pdf or other format)

Tags:

plot

r

I have more than 10 files (in the end some hundreds...). which I generated in R in png format saved into a folder.

My question: How could I save these files into a multiplot (e.g. 4 figures on one page arranged in 2 rows and 2 columns)?

I know that this is possible to incorporate inside a plot loop by using par(mfrow=c(2,2)) but how could I do this outside just calling the files in the folder after they are generated?

like image 328
kurdtc Avatar asked Oct 14 '14 13:10

kurdtc


1 Answers

Here a fast method to aggregate many png files:

  1. read your png using readPNG
  2. convert them to a raster , and plot them using grid.raster: very efficient.

Something like this :

library(png)
library(grid)
pdf('somefile1.pdf')
lapply(ll <- list.files(patt='.*[.]png'),function(x){
  img <- as.raster(readPNG(x))
  grid.newpage()
  grid.raster(img, interpolate = FALSE)

})
dev.off()

Edit : loading png , arranging them and merge them in the same pdf :

First you should store your png files in a list of grobs using rasterGrob :

plots <- lapply(ll <- list.files(patt='.*[.]png'),function(x){
  img <- as.raster(readPNG(x))
  rasterGrob(img, interpolate = FALSE)
})

Then save them using the excellent handy function marrangeGrob :

library(ggplot2)
library(gridExtra)
ggsave("multipage.pdf", marrangeGrob(grobs=plots, nrow=2, ncol=2))
like image 129
agstudy Avatar answered Oct 11 '22 14:10

agstudy