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:
p <- levelplot(raster, layers=1, margin = FALSE, col.regions=viridis, at=seq(0,1, len=100))
p + layer(sp.polygons(polygon, lwd=0.8, col='darkgray'))
Here is a reproducible example:
library(sp)
#get raster
data(meuse.grid)
coordinates(meuse.grid) = ~x+y
proj4string(meuse.grid) <- CRS("+init=epsg:28992")
gridded(meuse.grid) = TRUE
meuse.r<- raster(meuse.grid)
#get polygon
data("meuse.area")
meuse.area = SpatialPolygons(list(Polygons(list(Polygon(meuse.area)), "area")))
#plot
library(rasterVis)
library(viridis)
p <- levelplot(meuse.r, layers=1, margin = FALSE, col.regions=viridis, at=seq(0,1, len=100))
p + layer(sp.polygons(meuse.area, lwd=0.8, col='darkgray'))