R - plotting multiple rasters using matrix layout

layout, matrix, plot, r, raster

Solution

There may be an issue between S4 methods and layout() here. As a workaround, it seems to work to replace plot() with image(). Instead of plot(rast1, axes=F, ann=F, legend=F, box=F, useRaster=T), use image(rast1, axes=F, ann=F, asp=1) to get square image maps.

Problem

In R (Win64), I'm trying to plot a combination of raster images and histograms in a single plot window using the layout() command with a matrix defining the layout. Here's some sample code with simplified data: ``` library(raster) r <- raster(ncols=5, nrows=5, xmn=1, xmx=5, ymn=1, ymx=5) rast1 <- rasterize(expand.grid(1:5,1:5), r, rnorm(25)) rast2 <- rasterize(expand.grid(1:5,1:5), r, rnorm(25)) rast3 <- rasterize(expand.grid(1:5,1:5), r, rnorm(25)) layout(matrix(c(1,2,3,4,1,2,3,5,1,2,3,6), 3, 4, byrow=T)) layout.show(6) plot(rast1, axes=F, ann=F, legend=F, box=F, useRaster=T) plot(rast2, axes=F, ann=F, legend=F, box=F, useRaster=T) plot(rast3, axes=F, ann=F, legend=F, box=F, useRaster=T) hist(rnorm(100), ann=F, axes=F) hist(rnorm(100), ann=F, axes=F) hist(rnorm(100), ann=F, axes=F) ``` As you can see, I'm trying to plot three raster images (rast1, rast2, rast3) that span 1 column and 3 rows each, with 3 histograms beside them, each of which spans 1 column and 1 row. The layout.show() command gives the idea. When I run this code, it seems like the first plot (raster) command also resets the layout of the plot window, causing all subsequent plots to plot in a standard 3x4 grid (with the 5th plot now overlapping the first). The layout setup seems sound, as I can plot six histograms in the proper layout. But the raster plots mess things up. I suspect there is something about the plot() command in {raster} that is messing with the layout() command, but I have no idea why or how. Is there some other way to achieve this layout? Another raster-based command? Is there some way to reset the layout between raster plots? Thanks in advance.

Original source