I am using the Tigris package to download shape files with the code,
options(tigris_class = "SF")
While I can easily map polygons
ggplot(data=zctas) +
geom_sf(aes())
I am struggling to create a marker/point instead of a filled polygon (for example, a shape -- like a circle inside a zctas) as the shape file I've pulled down from tigris does not have a lat/long for the x and y AES mapping. The shape file has a "geometry" column, and I am wondering if I can use that?
The documentation here, https://ggplot2.tidyverse.org/reference/ggsf.html
appears to indicate the geom_sf can be used go create points? (I am guessing using the centroid of the zctas' polygon?) but I haven't been able to find an example? Grateful for any resources to identify code that maps points from this Tigris generated shape-file, and or tips and/or alternative approaches.
You're looking for stat_sf_coordinates()
, described here.
library(ggplot2)
nc <- sf::st_read(system.file("shape/nc.shp", package="sf"))
#> Reading layer `nc' from data source `/Library/Frameworks/R.framework/Versions/3.6/Resources/library/sf/shape/nc.shp' using driver `ESRI Shapefile'
#> Simple feature collection with 100 features and 14 fields
#> geometry type: MULTIPOLYGON
#> dimension: XY
#> bbox: xmin: -84.32385 ymin: 33.88199 xmax: -75.45698 ymax: 36.58965
#> epsg (SRID): 4267
#> proj4string: +proj=longlat +datum=NAD27 +no_defs
ggplot(nc) +
geom_sf()
ggplot(nc) +
geom_sf() +
stat_sf_coordinates()
#> Warning in st_point_on_surface.sfc(sf::st_zm(x)): st_point_on_surface may
#> not give correct results for longitude/latitude data
ggplot(nc) +
geom_sf() +
geom_point(
aes(color = SID74, size = AREA, geometry = geometry),
stat = "sf_coordinates"
) +
scale_color_viridis_c(option = "C") +
theme(legend.position = "bottom")
#> Warning in st_point_on_surface.sfc(sf::st_zm(x)): st_point_on_surface may
#> not give correct results for longitude/latitude data
Created on 2019-11-03 by the reprex package (v0.3.0)
One comment about the geometry = geometry
statement inside the aes()
call of the last example: Both geom_sf()
and stat_sf_coordinates()
will auto-map the geometry column if they find one in the dataset. However, geom_point()
doesn't know about geometry columns and therefore doesn't automap, thus we have to map manually.