Unable to map polygon over points and point density

Viewed 189

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: enter image description here 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?

1 Answers

The issue is that the geom_sf layer inherits the global aes x and y. However in s there are no vars X and Y. To prevent this simply set inherit.aes = FALSE in your call to 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)

Related