2

Solution to kurdtc's question does not work anymore:

library(grid)
library(png)

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

library(ggplot2)
library(gridExtra)

ggsave("Plots_Combined.png",width=8.5, height=11, 
        do.call(marrangeGrob, c(plots, list(nrow=2, ncol=1,top=NULL))))

The marrangeGrob function gives the following error: Error: nrow * ncol >= n is not TRUE , where 2 png files are in the current folder (it should work). Have there been any updates to the marrangeGrob function that affect this functionality?

steveb
  • 5,382
  • 2
  • 27
  • 36
Red
  • 23
  • 1
  • 5

1 Answers1

3

the list of parameters for marrangeGrob has changed recently; there is no need for do.call any longer, just use the grobs argument,

ggsave("Plots_Combined.pdf",width=8.5, height=11, 
       marrangeGrob(grobs = plots, nrow=2, ncol=1,top=NULL))

for png, you can't output multiple pages to a single file, but this trick could help,

ggsave("Plots_Combined%03d.png",width=8.5, height=11, 
       marrangeGrob(grobs = plots, nrow=2, ncol=1,top=NULL))
baptiste
  • 75,767
  • 19
  • 198
  • 294
  • Great answer! Thanks for your help baptiste. I had no idea about that change and my code stopped working out of nowhere. Regards. – Red Jul 30 '15 at 21:10
  • baptiste, now it actually gives another error: Error in ggsave("Plots_Combined%03d.png", width = 8.5, height = 11, marrangeGrob(grobs = plots, : plot should be a ggplot2 plot – Red Jul 30 '15 at 21:21
  • yep, it only works with the latest version of ggsave, and I think it's not yet in the released version of ggplot2. – baptiste Jul 30 '15 at 21:28
  • baptiste, is there any other method you think I should look at to be able to combine png files in the current folder to a single file? I've simplified my approach by only using the par function, but the resolution of the combined plot is incomparable. – Red Jul 30 '15 at 21:58
  • 1
    this approach should work, you don't have to use ggsave, use `png("file%03d.png") print(marrangeGrob(grobs = plots, nrow=2, ncol=1,top=NULL)); dev.off()` instead. – baptiste Jul 30 '15 at 23:32
  • baptiste, the solution showed worked perfectly. Thanks for your insights again, regards. – Red Jul 31 '15 at 18:17