Since sf is so new, support for it in ggplot2 is also very new. That means you’ll need to install the development version of ggplot2 from GitHub. That’s easy to do using the devtools package:
# install.packages("devtools") devtools::install_github("tidyverse/ggplot2")
Check that the install has succeeded by loading the tidyverse and then running
?geom_sf. If you can’t find the documentation for
geom_sf something has gone wrong.
Next we’ll load the tidyverse, sf, and create a couple of sample datasets.
library(tidyverse) library(sf) library(maps) nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE) states <- sf::st_as_sf(map("state", plot = FALSE, fill = TRUE))
The easiest way to get started is to supply an sf object to
ggplot() + geom_sf(data = nc)
You can supply other aesthetics: for polygons,
fill is most useful:
ggplot() + geom_sf(aes(fill = AREA), data = nc, colour = "white")
Note that ggplot2 takes care of setting the aspect ratio correctly.
When you include multiple layers, ggplot2 will take care of ensuring that they all have a common CRS.
ggplot() + geom_sf(data = states) + geom_sf(data = nc)
You can also combine with regular layers.
y positions are assumed be in the same CRS as the sf object.
ggplot() + geom_sf(data = nc) + annotate("point", x = -80, y = 35, colour = "red", size = 4)
You’ll need to use
coord_sf() for two reasons:
You want to zoom into a specified region of the plot by using
ggplot() + geom_sf(data = nc) + annotate("point", x = -80, y = 35, colour = "red", size = 4) + coord_sf(xlim = c(-81, -79), ylim = c(34, 36))
You want to override to use a specific projection. If you don’t specify the
crs argument, it just uses the one provided in the first layer. The following example uses “USA_Contiguous_Albers_Equal_Area_Conic”, which has EPSG ID
ggplot() + geom_sf(data = states) + coord_sf(crs = st_crs(102003))