14  Making Maps With ggplot Using Location Data

14.1 Call Libraries

Code
library(readr) # read CSV

library(dplyr) # data wrangling

library(sf) # simple features

library(ggplot2) # maps

14.2 Use read_csv to Read Text File with Client Data

Code
clients <- read_csv("./location-data/clients.csv")

14.3 Only Clients in Ann Arbor Area

Code
clients <- clients %>% 
  filter(latitude <= 42.33 &
           latitude >= 42.22 &
           longitude >= -83.8 &
           longitude <= -83.65)

14.4 Convert Clients to sf Object While Indicating Coordinate Reference System (CRS)

Code
point <- st_as_sf(clients, 
                  coords = c("longitude", "latitude"), 
                  crs = 4269) # A2 is NAD1983

# write to shapefile

st_write(point, 
         "./shapefiles/clients/clients.shp",
         append = FALSE) # replace; don't append

14.5 Read in Shapefile(s)

Code
city_boundary <- read_sf("./shapefiles/AA_City_Boundary/AA_City_Boundary.shp")

WashtenawRoads <- read_sf("./shapefiles/Roads/RoadCenterlines.shp")

AnnArborRoads <- st_crop(WashtenawRoads, 
                         city_boundary) # crop to only get A2 roads

14.6 Map

Code
ggplot(city_boundary) +
  geom_sf(alpha = .5) +
  geom_sf(data = AnnArborRoads, 
          color = "darkgrey") +
  geom_sf(data = point,
          aes(color = program),
          size = 3) +
labs(title = "Ann Arbor",
     subtitle = "Location of Program Clients") +
  scale_color_viridis_d() +
  scale_fill_viridis_d() +
  theme_minimal() +
  theme(plot.title = element_text(size = rel(2)), 
        axis.text = element_text(size = rel(.5)),
        legend.position = "bottom")