I am trying to use the stat_density_2d() function to create a heat map based on GPS coordinates and would like to crop the output to a polygon in ggplot(). Here is an example:
x_coord <- c(-83, -82, -82, -83, -83)
y_coord <- c(41, 41, 42, 42, 41)
xy_coords <- cbind(x_coord, y_coord)
library(sp)
poly <- Polygon(xy_coords)
polys <- Polygons(list(poly), 1)
sp.polys <- SpatialPolygons(list(polys))
set.seed(2)
lon <- c(rnorm(20, -82.2, 0.1), rnorm(20, -82.1, 0.04))
lat <- c(rnorm(20, 41.2, 0.1), rnorm(20, 41.1, 0.02))
lon_lat <- data.frame(lon = lon,
lat = lat)
ggplot() +
geom_polygon(data = sp.polys, aes(x_coord, y_coord), fill = 'transparent', color = 'black') +
stat_density_2d(data = lon_lat, aes(x = lon, y = lat, fill = ..level.., alpha = 0.3), geom =
'polygon') +
scale_fill_gradientn(colours=rev(brewer.pal(7, "Spectral"))) +
scale_x_continuous(limits = c(-83.25, -81.75)) +
scale_y_continuous(limits = c(40.75, 42.25))
which produces this figure
Is there a way to crop the stat_density output to remove the portion outside the square? Any thoughts or suggestions are greatly appreciated.