I'm trying to ggplot2::facet_wrap a stack of rasters, and then call geom_raster to add more rasters on top of the previously mapped raster stack.
Here is a very simple example dataset to re-create what I've tried:
#Load packages
library(raster)
library(ggplot2)
# create a raster
set.seed(11)
r <- raster(nrows = 10, ncols = 10, res = 30, xmn = 267195, xmx = 267375, ymn = 4016985, ymx = 4017135)
r <- setValues(r, runif(ncell(r), min = -10000, max = 10000))
# create a raster stack
rr <- lapply(1:4, function(i) setValues(r, runif(ncell(r), min = -10000, max = 10000)))
r_stack <- stack(rr)
crs(r_stack) <- "+proj=utm +zone=43 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0"
prj <- crs(r_stack)
plot(r_stack)
# use gplot w/ facet_wrap
library(rasterVis)
gplot(r_stack) +
geom_raster(aes(fill = value)) +
facet_wrap(~ variable) +
scale_fill_gradientn(colours = rev(terrain.colors(225))) +
coord_equal()
# create another raster stack
ss <- lapply(1:4, function(i) setValues(r, runif(ncell(r), min = -1, max = 1)))
s_stack <- stack(ss)
crs(s_stack) <- "+proj=utm +zone=43 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0"
prj <- crs(s_stack)
# plot r_stack and call geom_raster to plot s_stack on top
gplot(r_stack) +
geom_raster(aes(fill = value)) +
facet_wrap(~ variable) +
scale_fill_gradientn(colours = rev(terrain.colors(225))) +
coord_equal() +
geom_raster(data=s_stack, aes(x=x,y=y))
#Error: `data` must be a data frame, or other object coercible by `fortify()`, not an S4 object with class RasterStack
#Run `rlang::last_error()` to see where the error occurred.
I realize that the new raster would essential cover up the previous raster plot, but the raster data that I'm calling in the 2nd geom_raster call will have different data to display, most of which will be 'gaps' or NA.