I am analysing my sfc_POINT dataset using ggplot2::stat_density_2d
. I seems, though, that the resulting polygons get all wonky at the edge of the dataset bounding box. For whatever reason, ggplot2 can't seem to draw polygons further than the source dataframe edges.
How do I fix the density polygons? Is there a way to extend the bounding box for stat_density_2d
somehow?
For this question I am able to reproduce my problem with a random sample point data. Please see the code here:
library(dplyr)
library(sf)
library(geofi)
library(ggplot2)
# Finland municipalities
muns <- geofi::get_municipalities(year = 2022)
# Create sample points
points <- sf::st_sample(muns, 50) %>% as.data.frame()
points[c("x", "y")] <- sf::st_coordinates(points$geometry)
p4 <- ggplot() +
geom_sf(data = muns) +
coord_sf(default_crs = sf::st_crs(3067)) +
stat_density_2d(geom = "polygon",
data = points,
aes(x = x, y = y, fill = ..level..),
alpha = 0.75) +
scale_fill_viridis_c() +
geom_point(data = points, aes(x = x, y = y), alpha = 0.5)
p4