rrastersubplotgridextralevelplot

How can I add a subplot within a plot using levelplot in R?


I would like to add a subplot in my main levelplot, something similar to this image. I want lat/lon axis for both my maps but I have not managed to find a way to do this with the levelplot. Also, I've seen this question but has no answer. I am quite confused about the subplot and the new par(), so I would really like some help.

library("raster")
library ("rasterVis")
library("viridis")

r <- raster(system.file("external/test.grd", package="raster"))#subplot
r2<-r/2 #main plot
ckey <- list(labels=list(cex=1.5), height=1,space='top')
levelplot(r2,colorkey=ckey,margin=FALSE,xlab="", ylab="",col.regions=viridis,at=seq(100,500, len=20),
          scales=list(x=list(cex=1.5),y=list(cex=1.5))) #from this point, I do not know how to add a subplot

Solution

  • grid.arrange from the gridExtra package can do that for you

    library(raster)
    library(rasterVis)
    library(viridis)
    library(gridExtra)
    
    r <- raster(system.file("external/test.grd", package = "raster")) # subplot
    r2 <- r / 2 # main plot
    ckey <- list(labels = list(cex = 1.5), height = 1, space = "top")
    
    lv1 <- levelplot(r2,
      colorkey = ckey, margin = FALSE, xlab = "", ylab = "", col.regions = viridis, at = seq(100, 500, len = 20),
      scales = list(x = list(cex = 1.5), y = list(cex = 1.5))) # from this point, I do not know how to add a subplot
    
    lv2 <- levelplot(r2,
      colorkey = ckey, margin = FALSE, xlab = "", ylab = "", col.regions = viridis, at = seq(100, 500, len = 20),
      scales = list(x = list(cex = 1.5), y = list(cex = 1.5)))
    
    lay <- rbind(
      c(1, 1, NA, NA, NA),
      c(1, 1, 2, 2, 2),
      c(NA, NA, 2, 2, 2),
      c(NA, NA, 2, 2, 2)
    )
    
    grid.arrange(lv1, lv2, layout_matrix = lay,
                 top = "Figure 1.", 
                 bottom = "bottom\nlabel")
    

    Created on 2019-11-22 by the reprex package (v0.3.0)