Split a map into two separate maps by latitude or longitude

Viewed 359

Is there a way to slice a ggplot2 map into two separate maps? I have one large map with id labels that are illegible. I want to split the map vertically into two distinct maps, preferably with an overlapping area so that each polygon would show up whole in at least one map.

Here's a reproducible example. I would want to split the map into a northern one at 35 degrees north and then into a southern one at 35.5 degrees north (giving an overlap between 35 and 35.5 in both). (While I realize it might make more sense with this example to split the other way, my actual map is long vertically.)

library(sf)
library(ggplot2)

sf_nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)
plot <- ggplot2::ggplot(sf_nc) +
  geom_sf(aes(color = NAME)) +
  geom_sf_text(aes(label = NAME)) 

enter image description here

1 Answers

Maybe this is what you are looking for.

  1. Following this post I first make use of st_crop to split the sf df by latitude and extract the FIPS codes for south and north regions.
  2. The FIPS codes are then used to split the sf dataframe into two which ensures that regions on the dividing line are shown in total in both maps.
  3. Finally, I add an ID and bind both dfs back together for easy plotting with facet_wrap
library(sf)
library(ggplot2)
library(dplyr)

sf_nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)

# Get FIPS/regiona codes for north regions
south <- st_crop(sf_nc, xmin=-180, xmax=180, ymin=-90, ymax=35.5) %>% 
  pull(FIPS)

north <- st_crop(sf_nc, xmin=-180, xmax=180, ymin=35.5, ymax=90) %>% 
  pull(FIPS)

# Make sf df for north and south
sf_nc_1 <- filter(sf_nc, FIPS %in% south) %>% 
  mutate(id = "South")
sf_nc_2 <- filter(sf_nc, FIPS %in% north) %>% 
  mutate(id = "North")

# Bind together for using facet_wrap
sf_nc_split <- rbind(sf_nc_1, sf_nc_2)

ggplot2::ggplot(sf_nc_split) +
  geom_sf(aes(color = NAME)) +
  geom_sf_text(aes(label = NAME), size = 2) +
  guides(color = FALSE) +
  facet_wrap(~id, ncol = 1) +
  theme_void()

Related