r - 无法在点和点密度上映射多边形
问题描述
这个玩具示例:
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
我究竟做错了什么?
解决方案
问题是该geom_sf
层继承了全局 aesx
和y
. 但是,s
没有 varsX
和Y
. 为了防止这种情况,只需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)
推荐阅读
- linux - SQLite Studio 键盘输入损坏
- c# - 转换器不能应用于需要 IValueConverter 类型的属性
- django - 如何使用 zip() 函数插入数据
- r - 使用一列作为开始,另一列作为框的停止绘制图
- jenkins - currentBuild.changeSets 在管道 Jenkins 中通过提交剪切消息
- javafx - 为什么我的标签显示“String called name”Null
- javascript - 为什么 window.onload 只能在第一个数组值上按预期工作,而我必须重新加载页面以获取其他数组值?
- python - 与 groupby 和 mean 结合使用时,Fillna 不起作用
- dart - Flutter CustomScrollView 和 Scoped 模型问题
- jpa - 将 EJB 2 CMP 实体 bean 迁移到 EJB 3 JPA 实体时如何处理 FinderException?