Add Spatrastermap to existing Spatrastermap

50 Views Asked by At

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)

2

There are 2 best solutions below

2
On BEST ANSWER

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()

elevation data

0
On

With these data

library(terra)
r <- rast(system.file("ex/elev.tif", package="terra"))
x <- classify(r, cbind(-Inf, 400, NA))

You can do

plot(as.contour(r))
plot(x, add=TRUE)

Or something like

plot(x)
cntr <- as.contour(r, add=TRUE)
plot(x, add=TRUE)