Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrange multiple (32) .png files in a grid

Tags:

r

png

grid-layout

I've been pulling my hair out for the past week trying to figure out elementary R coding but can't seem to get anywhere (haven't used R since 2013 not that its a great excuse).

All I want is a 4x8 grid made up of 32 .png files (maps I've made), and I want to do it without loading one image file at a time (http://www.statmethods.net/advgraphs/layout.html).

So I think I can load the images within the folder writing (please correct me if my beliefs are bs)

img <- list.files(path='c:/a',patt='compo[0-32].*',full.names=T)

Then I was thinking maybe in the lines of par(mfrow=c()), layout, grid.arrange (writing png plots into a pdf file in R), grid.raster (How to join efficiently multiple rgl plots into one single plot?) - which I've read up on and experimented with accordingly not resulting in anything worthwhile..

The latter I employed only with the following outcome enter image description here

It made me giggle. I don't really think lattice is the way to go anyway.

Any help would be greatly appreciated!

like image 263
IdaFish Avatar asked Aug 18 '14 09:08

IdaFish


2 Answers

Another approach is to read the PNG images with readPNG then use grid and gridExtra:

library(png)
library(grid)
library(gridExtra)

plot1 <- readPNG('plot1.png')
plot2 <- readPNG('plot2.png')

grid.arrange(rasterGrob(plot1),rasterGrob(plot2),ncol=1)

Alternative: If you want to save the plot using ggsave, instead of grid.arrange you can use

tmp <- arrangeGrob(rasterGrob(plot1),rasterGrob(plot2),ncol=1)
ggsave('filename.png',tmp,width=12,height=5)
like image 192
Richard DiSalvo Avatar answered Oct 16 '22 06:10

Richard DiSalvo


Not sure what your concern is about loading all the image files -- how else could you read their data to create the new image?

ETA: to load the files, I'd just use png::readPNG . One way to collect the images would be(12 images selected here)

filenames<-dir(pattern='compo')
foo<-list()
for(j in 1:12) foo[[j]]<-readPNG(filenames[j]

If you're willing to load them and use the base plot tools, then layout is the command you want. E.g., for 12 images loaded

layout(matrix(1:12,nr=4,byr=T))
for (j in 1:12) plot(foo[[j]])
like image 24
Carl Witthoft Avatar answered Oct 16 '22 07:10

Carl Witthoft