4

I want to plot both a raster layer and a polygon layer using rasterVis::levelplot(), however, I want to have the polygon layer appear under the raster layer.

library(sp)
library(rgeos)
library(raster)
library(rasterVis)

r <- raster(xmn = 0, xmx = 1, ymn = 0, ymx = 1, nrows = 100, ncols = 100,
            crs = "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs")
r[] <- rnorm(100 * 100)
r[sample(1:ncell(r), ncell(r) / 2)] <- NA

pt <- data.frame(x = 0.5, y = 0.5)
coordinates(pt) <- ~ x + y
proj4string(pt) <- projection(r)
pt_buff <- gBuffer(pt, width = 0.25)
levelplot(r, margin = FALSE) +
  layer(sp.polygons(pt_buff, fill = "grey40", col = NA))

I want the circle under the raster layer: enter image description here

4

Use under = TRUE inside the layer function, or the wrapper function layer_:

levelplot(r, margin = FALSE) +
    layer_(sp.polygons(pt_buff,
                      fill = "grey40",
                      col = NA))
  • Thanks! Switching this to the accepted answer, since it more succinctly answers the question. – Matt SM Jun 19 '17 at 12:20
4

You can create custom panel functions in lattice-based plot functions:

levelplot(r, margin = FALSE,
          panel=function(...) {
            sp.polygons(pt_buff, fill = "grey40", col = NA)
            panel.levelplot(...)
          }) 

levelplot

  • thanks, this is perfect! I know nothing about lattice plotting, so never would have come across this on my own – Matt SM Jun 15 '17 at 13:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.