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?
Here a fast method to aggregate many png files:
readPNG
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()
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With