It really depends on what you want to achieve.
- You can either do the selection at the data level, and discard the grid cells that are not entirely contained by the country borders. This is good if you want to do some calculation on the resulting raster, but the cells look somewhat ragged.
- Or you can keep the data as they are, and keep all the action at the plotting level = overlay the grid cells with a white mask cut to the shape of country borders. The data will remain as they were, but the plot will be nice & even.
The first option - built on raster::mask() - is in my code sample above.
The second, masking, does not require {raster} and makes do with {sf} only:
library(tidyverse)
library(sf)
borders <- readRDS(url("https://biogeo.ucdavis.edu/data/gadm3.6/Rsf/gadm36_IRN_0_sf.rds"))
DFgrid <- data.frame(
lon=c(59.25, 59.75, 60.25, 60.75, 61.25, 61.75, 57.25, 57.75, 58.25, 58.75, 59.25, 59.75, 60.25, 60.75, 61.25, 61.75, 62.25, 57.25, 57.75, 58.25, 58.75, 59.25, 59.75, 60.25, 60.75, 61.25, 61.75, 62.25, 62.75, 53.25),
lat=c(25.25, 25.25, 25.25, 25.25, 25.25, 25.25, 25.75, 25.75, 25.75, 25.75, 25.75, 25.75, 25.75, 25.75, 25.75, 25.75, 25.75, 26.25, 26.25, 26.25, 26.25, 26.25, 26.25, 26.25, 26.25, 26.25, 26.25, 26.25, 26.25, 26.75),
value= rnorm(30)
)
mask <- borders %>%
st_bbox() %>%
st_as_sfc() %>%
st_buffer(5) %>%
st_difference(borders) %>%
st_as_sf()
my_year <- theme_bw() + theme(panel.ontop=TRUE, panel.background=element_blank())
my_fill <- scale_fill_distiller('',palette='Spectral',
breaks = c(-2,0,2))
fig = ggplot() + geom_tile(data = DFgrid, aes(y=lat, x=lon, fill=value)) + my_year + my_fill +
geom_sf(data = mask, fill = "white", color = NA) +
coord_sf(xlim=c(44.05, 63.35), ylim=c(25.05, 39.75)) +
borders('world', xlim=c(44.05, 63.35), ylim=c(25.05, 39.75), colour='black')+
xlab('Longitude (°E)')+ ylab('Latitude (°N)')+
theme(panel.grid=element_blank(),
panel.border = element_rect(colour = "black", fill=NA,size=.7))
print(fig)
The final choice is up to you 