0

我正在尝试使用 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 输出以删除正方形外的部分?非常感谢任何想法或建议。

4

1 回答 1

0

我无法找到将 stat_density_2d 输出裁剪为多边形的方法,但使用下面的代码可以掩盖多边形外部的区域。下面的代码假定您已经使用问题中发布的代码来创建多边形和 stat_density_2d 输出。

library(sp)
library(ggplot2)
library(RColorBrewer)
library(rgeos)
library(raster)

x_coord2 <- c(-83.2, -81.8, -81.8, -83.2, -83.2)
y_coord2 <- c(40.8, 40.8, 42.2, 42.2, 40.8)

xy_coords2 <- cbind(x_coord2, y_coord2)

poly2 <- Polygon(xy_coords2)
polys2 <- Polygons(list(poly2), 1)
sp.polys2 <- SpatialPolygons(list(polys2))

r <- raster(x = extent(sp.polys2))
res(r) <- 0.003
r <- setValues(r, 1)
r <- mask(r, sp.polys, inverse = T)

rdf <- data.frame(rasterToPoints(r))


ggplot() +
  stat_density_2d(data = lon_lat, aes(x = lon, y = lat, fill = ..level..), alpha = 
                  0.7, 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)) +
  geom_tile(data = rdf, aes(x, y), fill = 'white') +
  geom_polygon(data = sp.polys, aes(x_coord, y_coord), fill = 'transparent', color = 
               'black') +
  theme_bw() +
  theme(panel.grid.minor = element_blank(), 
        panel.grid.major = element_blank())

在此处输入图像描述

于 2020-12-21T01:18:41.307 回答