I am trying to create map by overlaying a polygon shape file over a raster layer using rasterVis package. I am able to perform this function with no problem with plot() function in raster package but I'd like to customize the colors. For some reason the levelplot() doesn't allow me to overlay raster and polygons. My first attempt was:
levelplot(raster, margin=FALSE, col.regions=viridis, at=seq(0,1, len=100)+ layer(sp.polygons(polygon)))
and I get these error:
Error in +.trellis
(seq(0, 1, len = 100), layer(sp.polygons(polygon))) :
inherits(object, "trellis") is not TRUE
Then I tried using latticeExtra:
levelplot(raster, margin=FALSE, col.regions=viridis, at=seq(0,1, len=100)+ latticeExtra::layer(sp.polygon(polygon)))
I get the same error as above. I also tried other proposed solutions such as running the line dev.off()and restarting R and I get:
Error in dev.off() : cannot shut down device 1 (the null device)
And finally I tried detaching ggplot2 but I still get the same "trellis" error message. I don't know how to interpret this error message. I double-checked that both files had the same CSR just in case that was the problem. Also, note that the raster layer is plotted with no problem adding the polygon produces the error. Any ideas?
This should work:
Here is a reproducible example: