I'm trying to plot shapefiles in R using ggplot2
and sf
to call geom_sf
but it's throwing errors that I can't seem to work around. I am able to plot the SpatialPolygonsDataFrame without issue using plot()
but I'd like to work with ggplot
and geom_sf
if possible.
The shapefiles can be found here: https://data.cityofchicago.org/Facilities-Geographic-Boundaries/Boundaries-Neighborhoods/bbvz-uum9
Here's what should be a MWE:
library(ggplot2)
library(sf)
library(rgdal)
nbrhd_shp <- readOGR(dsn = shapefile_filepath, layer = "geo_export_00bf6ede-a61b-4746-8c69-e1510a184344")
class(nbrhd_shp)
plot(nbrhd_shp)
these both work. The class(nbrhd_shp)
returns as expected:
> class(nbrhd_shp)
[1] "SpatialPolygonsDataFrame"
attr(,"package")
[1] "sp"
But when I try to plot with ggplot
I get a blank plot with coordinate labels on the axes and an error message:
ggplot(nbrhd_shp) +
geom_sf(data = nbrhd_shp@data, aes(geometry = nbrhd_shp@polygons))+
coord_sf(crs = st_crs(nbrhd_shp))
Regions defined for each Polygons
Warning message:
Computation failed in `stat_sf()`
Caused by error in `UseMethod()`:
! no applicable method for 'st_bbox' applied to an object of class "list"
I think you should convert it to an sf object first.
nbrhd_shp <- st_as_sf(nbrhd_shp)
ggplot(nbrhd_shp) + geom_sf()