rggplot2r-packagetigris

Zooming in on map / choropleth using ggplot2 & tigris in R


I have the following code which works to create a map of NYC counties 061 and 047:

library(tidycensus)
library(tidyverse)
library(tigris)

ny_data <- get_acs(
  geography = "tract",
  variables = "B19013_001",
  state = "NY",
  county = c("061","047"),
  year = 2019,
  geometry = TRUE,
  cb = FALSE) %>%
  st_transform(26918) %>%
  erase_water(year = 2019)

ggplot(data=ny_data, aes(fill = estimate)) + 
  geom_sf(color = NA) + 
  scale_fill_viridis_c(option = "magma") +
  theme_minimal() +
  theme(panel.grid.major = element_blank(), 
        panel.grid.minor = element_blank(),
        axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))

NYC map1

However, I want to zoom in on this map slightly. I know the coord_sf function is what I should use. But, when I add the function to my ggplot I get unexpected results:

ggplot(data=ny_data, aes(fill = estimate)) + 
  geom_sf(color = NA) + 
  coord_sf(xlim = c(-74.05, -73.9), ylim = c(40.6, 40.85)) +
  scale_fill_viridis_c(option = "magma") +
  theme_minimal() +
  theme(panel.grid.major = element_blank(), 
        panel.grid.minor = element_blank(),
        axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))

NYC map2

I suspect this may have something to do with coordinate systems, but I am not savvy in geospatial data and do not know how to fix it. It may also have something to do with the "st_transform" function used to help me erase water area. Any help would be appreciated.

Summary: I attempted to use the coord_sf function to zoom in on a map area, x and y limits of latitude and longitude do not work as expected.


Solution

  • I have solved my own question, posting here for others who may have the same issue.

    As noted above, the issue was in the "st_transform" function. I believe, but am not sure, that that function was essentially transforming my geodata for just NY counties 061 and 047 to a projection on the entire state of NY (26918 is the EPSG code for NY https://epsg.io/26918).

    This code works:

    ny_data <- get_acs(
      geography = "tract",
      variables = "B19013_001",
      state = "NY",
      county = c("061","047"),
      year = 2019,
      geometry = TRUE,
      cb = FALSE) %>%
      #st_transform(26918) %>%
      erase_water(year = 2019)
    
    ggplot(data=ny_data, aes(fill = estimate)) + 
      geom_sf(color = NA) + 
      coord_sf(xlim = c(-74.05, -73.9), ylim = c(40.6, 40.85)) +
      scale_fill_viridis_c(option = "magma") +
      theme_minimal() +
      theme(panel.grid.major = element_blank(), 
            panel.grid.minor = element_blank(),
            axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))