无法在点和点密度上映射多边形

Unable to map polygon over points and point density

这个玩具示例:

library(dplyr)
library(sf)
library(ggplot2)

# create random points
p <- runif(50, 0, 11) %>% cbind(runif(50, 0, 11)) %>% st_multipoint %>% st_sfc %>% st_cast("POINT") %>% st_sf
# append coordinates for ggplot
p <- cbind(p, st_coordinates(p))

# plot points, point density
ggplot(p, aes(x=X, y=Y)) + geom_point() + 
  stat_density2d(geom="tile", aes(fill=..density..), contour=F, alpha=.5, data=p)

...returns: 尝试添加多边形:

# create polygon
s <- rbind(c(1, 1), c(10, 1), c(10, 10), c(1, 10), c(1, 1)) %>% list %>% st_polygon %>% st_sfc %>% st_sf

# plot points, point density and polygon
ggplot(p, aes(x=X, y=Y)) + geom_point() + 
  stat_density2d(geom="tile", aes(fill=..density..), contour=F, alpha=.5, data=p) + 
  geom_sf(data=s, fill=NA)

...returns:

Error in FUN(X[[i]], ...) : object 'X' not found

我做错了什么?

问题是 geom_sf 层继承了全局 aes xy。但是在 s 中没有变量 XY。为防止这种情况,只需在调用 geom_sf:

时设置 inherit.aes = FALSE
library(dplyr)
library(ggplot2)

# create random points
p <- runif(50, 0, 11) %>% cbind(runif(50, 0, 11)) %>% st_multipoint %>% st_sfc %>% st_cast("POINT") %>% st_sf
# append coordinates for ggplot
p <- cbind(p, st_coordinates(p))
# create polygon
s <- rbind(c(1, 1), c(10, 1), c(10, 10), c(1, 10), c(1, 1)) %>% 
  list %>% 
  st_polygon %>% 
  st_sfc %>% 
  st_sf

# plot points, point density and polygon
ggplot(p, aes(x=X, y=Y)) + geom_point() + 
  stat_density2d(geom="tile", aes(fill=..density..), contour=F, alpha=.5, data=p) + 
  geom_sf(data=s, fill=NA, inherit.aes = FALSE)