我正在尝试使用 stat_density_2d() 函数创建基于 GPS 坐标的热图,并希望将输出裁剪为 ggplot() 中的多边形。这是一个例子:
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))
产生这个数字
有没有办法裁剪 stat_density 输出以删除正方形外的部分?非常感谢任何想法或建议。