8

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?

zx8754
  • 52,746
  • 12
  • 114
  • 209
kurdtc
  • 1,551
  • 5
  • 21
  • 39

1 Answers1

8

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))
baptiste
  • 75,767
  • 19
  • 198
  • 294
agstudy
  • 119,832
  • 17
  • 199
  • 261
  • this is great for writing all files into one pdf file. I am however struggling to incorporate something like `par(mfrow=c(2,2))` so that I get more than one graph per page... – kurdtc Oct 14 '14 at 21:29
  • what command controls the title (page 1 of ...), at the moment the size of the title is huge? – kurdtc Oct 15 '14 at 07:02
  • 1
    @baptiste: When I set `do.call(marrangeGrob, c(plots, list(nrow=2, ncol=2)), top=NULL)`, this won't remove the number of pages and gives me an error. How could I control the size of the font or get rid of it completely? – kurdtc Oct 15 '14 at 10:11
  • 1
    you want all the options in the `list()` – baptiste Oct 15 '14 at 11:06
  • @baptiste: is it also possible to arrange the resulting output in landscape format? haven't found anything in the documentation. – kurdtc Oct 15 '14 at 21:49
  • 1
    the pdf (or any other) device lets you set width and height to whatever you want, so if you set width>height, that's landscape. I tend to stay away from the `paper` setting, personally. You can pass all those options through ggsave. – baptiste Oct 15 '14 at 22:00