首页 > 解决方案 > 无法在点和点密度上映射多边形

问题描述

这个玩具示例:

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)

...返回: 在此处输入图像描述 尝试添加多边形:

# 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)

...返回:

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

我究竟做错了什么?

标签: rggplot2sf

解决方案


问题是该geom_sf层继承了全局 aesxy. 但是,s没有 varsXY. 为了防止这种情况,只需inherit.aes = FALSE在您的调用中设置geom_sf

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)


推荐阅读