This toy example:
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:
Trying to add a polygon:
# 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
What am I doing wrong?
