Search code examples
rlatticegridextralevelplotrastervis

rasterVis - setting the bottom plots in the middle with levelplot


I am using the awesome rasterVis to create a panel with maps that have the same extent (i.e. same spatial coverage) but that show different features (i.e. each with its own legend).

This is what it looks like so far:

library(raster)
library(rasterVis)
library(RColorBrewer)
library(gridExtra)

# make-up data
r <- raster(system.file("external/test.grd", package="raster"))
s <- stack(r, r*2, r*3, r*4, r*5)
names(s) <- paste0("Field ",seq(1,5))

# pre-allocate list
l <- vector("list", length=nlayers(s))

# define theme for plots
my.theme <- rasterTheme(region=brewer.pal(11,'RdYlGn'))

# loop over stack layers to fill list
for (n in (1:nlayers(s))){
  
  l[[n]] <- levelplot(s[[n]], margin=F, main=names(s[[n]]), par.settings=my.theme)
  
}

# plot combined maps
grid.arrange(l[[1]], l[[2]], l[[3]], l[[4]], l[[5]], ncol=3)

enter image description here

Note that the default positioning for the maps is:

a b c
d e

However, I would like to have a finer control on the positioning. Specifically, I would like to "center" the bottom two facets in order to distribute the void space more evenly on the sides of the plot.

In other words, the placement I am looking for would look like:

a b c
 d e

How can I achieve this? I looked up the documentation for (grid.arrange), but couldn't find any option the would solve my problem.

Thanks in advance for any hints.


Solution

  • Here's an approach with cowplot::plot_grid inspired by this answer

    library(cowplot)
    top <- plot_grid(l[[1]], l[[2]], l[[3]],
                     ncol=3)
    bottom <- plot_grid(NULL, l[[4]], NULL,  l[[5]], NULL,
                        ncol=6, rel_widths=c(0.12,0.34,0.12,0.34,0.06))
    plot_grid(top, bottom,
              ncol=1, rel_heights=c(1,1))
    

    enter image description here

    You can modify the rel_widths in the bottom plot_grid call to get it just like you like.