So I have 4 images in the following format
> dim(images)
[1] 4 32 32 3
Each image is 32x32 pixels in a rgb format, where each pixel takes a value in [0,1]. I can plot one image at the time with
images2 <- rgb(images[1,,,1],images[1,,,2],images[1,,,3])
dim(images2) <- dim(images[1,,,1])
grid.raster(images2, interpolate=F)
How can I get all four images in one plot? par(mfrow=c(2,2))
does not seem to work, and I've searched the forum and tried gridArrange
without success.
Should I turn to lattice, ggplot? I'm new to raster objects so I don't know how to approach the problem.
Thanks
using rasterGrob and borrowing from the gridExtra package should do the trick:
library(gridExtra)
## Let's create some imgaes, for us who don't have your data:
if(!exists("images")) {
random.rgb <- floor( runif( n=4*32*32*3, min=0, max=256 ) ) / 255
images <- array( random.rgb, dim=c(4,32,32,3) )
}
## create a list of the rasters, note, have to use rasterGrob for this:
rgb.images <- lapply( 1:4, function(i) {
r <- rgb( images[i,,,1], images[i,,,2], images[i,,,3] )
dim(r) <- dim( images[1,,,1] )
rasterGrob(r)
})
grid.arrange( grobs=rgb.images )
notice that with grid.arrange
from gridArrange you need to use the grobs argument as you are supplying a list, and can't simply use the first positional argument.
Here's an additional approach, using the raster class from grDevices instead, which makes it easier to use with the normal plot controls (par etc):
rgb.images2 <- lapply( 1:4, function(i) {
r <- rgb( images[i,,,1], images[i,,,2], images[i,,,3] )
dim(r) <- dim( images[1,,,1] )
as.raster(r)
})
par(mfrow=c(2,2))
for( i in 1:4 ) {
plot( rgb.images2[[i]] )
title( paste("Figure",i) )
}