I would like to combine the map p with the map x in the following way: at those points where the plot x is white, I would like to see plot p (as first layer), and for the colored points the plot x, as second layer.
f = system.file("ex/elev.tif", package="terra")
r = rast(f)
p <- ggplot() + geom_spatraster_contour(data=r)
plot(p)
x = classify(r, cbind(-Inf, 400, NA))
plot(x)
You can get the desired output using geom_spatraster_contour
and geom_spatraster
. You just need to add the layers in order of appearance (first layers are plotted on the bottom and the last ones on top) and use one of the scale_fill_*
functions to set the fill palette and define the NA color.
library(terra)
library(ggplot2)
library(tidyterra)
ggplot() +
geom_spatraster_contour(data=r) +
geom_spatraster(data = x, aes(fill = elevation)) +
scale_fill_gradientn(colours = rev(terrain.colors(10)),
na.value = "transparent") +
theme_minimal()