7

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.

Josh O'Brien
  • 159,210
  • 26
  • 366
  • 455
David Roberts
  • 617
  • 1
  • 11
  • 23
  • The `plot` function is really a variety of functions that will get dispatched on the basis of the class of the first argument to it. You need to look at the particular function for the class of the object you are passing to it. (Probably `plot.raster`) – IRTFM Aug 27 '12 at 01:20

1 Answers1

5

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.

dcarlson
  • 10,936
  • 2
  • 15
  • 18