I want to create a polygon using a linestring within the sf universe. I am generating a map of a coastline and I want the area that is water to be blue and the area that is land to be tan. Because tigris::counties()
data include county-designated territory that extends into the ocean, that format is undesirable. tigris
also offers tigris::coastline()
, which includes a detailed linestring representing the coast, however I can't apply fill values to the "right side" of a line. Therefore, I would like to "complete" the polygon that is defined as the coastline (object my_coast
below) and the upper right corner of the bounding box.
## Import packages
library(tigris)
library(tidyverse)
library(sf)
## Define a bounding box
my_bbox = st_bbox(c(xmin = -121, xmax = -120.7,
ymin = 35.1, ymax = 35.3),
crs = 4326)
## County boundaries extend into the ocean
my_counties = tigris::counties(state = "California") %>%
st_transform(st_crs(my_bbox)) %>%
st_crop(my_bbox)
## Coastline is the interesting part
my_coast = tigris::coastline() %>%
st_transform(st_crs(my_bbox)) %>%
st_crop(my_bbox)
## Plot data. Shown are the county "boundary" data as solid line
## and coastline data as dashed line
ggplot() +
geom_sf(data = my_counties,
col = "grey40",
fill = "tan") +
geom_sf(data = my_coast,
col = "black",
size = 0.2,
lty = 2) +
coord_sf(expand = FALSE) +
theme(panel.background = element_rect(fill = "lightblue"))