I'm trying to create a smoothed map for a number of points in R, and I did not find a perfect solution here.
library(mapchina)
library(sf)
library(dplyr)
library(ggplot2)
# Create some sample data
sf_beijing = china %>%
filter(Code_Province == '11') %>%
st_transform(4326)
sf_points = data.frame(
lat = c(39.523, 39.623, 40.032, 40.002, 39.933, 39.943, 40.126, 40.548),
lon = c(116.322, 116, 116.422, 116.402, 116.412, 116.408, 116.592, 116.565)
) %>%
st_as_sf(coords = c("lon", "lat"), crs = 4326)
# Plot the boundary for Beijing and the points
ggplot() +
geom_sf(data = sf_beijing, fill = NA) +
geom_sf(data = sf_points, color = 'red') +
theme_test()
In addition, I found this solution to create a smoothed map for sf
points. The issue for this solution is that the smoothed map is not filled entirely in Beijing's boundary, and some of the smoothed parts go beyond the boundary.
ggplot() +
stat_density_2d(data = sf_points,
mapping = aes(x = purrr::map_dbl(geometry, ~.[1]),
y = purrr::map_dbl(geometry, ~.[2]),
fill = stat(density)),
geom = 'tile',
contour = FALSE,
alpha = 0.8) +
geom_sf(data = sf_beijing, fill = NA) +
geom_sf(data = sf_points, color = 'red') +
scale_fill_viridis_c(option = 'magma', direction = -1) +
theme_test()
ggsave('p1.png', width = 7, height = 8)
My question is: is there a way to create a smoothed map for these points and the smoothed map fills perfectly within the external boundary (no white space and no ``trespass'')?