这个玩具示例:
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
我在做什么错了?
答案 0 :(得分:3)
问题在于geom_sf
层继承了全局aes x
和y
。但是在s
中,没有变量X
和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)