I'm trying to crop a heat map (or "geom_tile") within a geographical boundary.
I define a random data frame for a heat-map along longitude and latitude coordinates.
set.seed(20)
lon = seq(from = 3.4, to = 6.3, by = 0.1)
lat = seq(from = 13.3, to = 10.1, by = -0.1)
lati <- c()
long <- c()
for (i in 1:length(lat)) {
for (j in 1:length(lon)) {
lati <- c(lati,lat[i])
long <- c(long,lon[j])
}
}
vals = rnorm(length(lati))
df <- data.frame(
longitude=long,
latitude=lati,
value=vals)
Then I make geographical boundary, specifically for Kebbi state in Nigeria.
library(raster)
library(sf)
nga <- getData('GADM', country='NGA', level=1)
keb <- subset(nga,NAME_1 %in% "Kebbi")
keb2 <- st_as_sf(keb)
Then I combine the heat map and geographical boundaries:
library(ggplot2)
tilekeb <- ggplot() + geom_tile(data=df,aes(x=longitude,y=latitude,fill=vals),alpha=1/2,color="black",size=0) +
geom_sf(data = keb2, inherit.aes = FALSE, fill = NA)
My aim is cut-out (crop) the part that is outside the boundary, leaving the heatmap only within the confined geographical boundary. Does anybody have ideas on how to do that in R/ggplot?
Thank you

lati <- numeric(length(lon) *length(lat))- tjebo