按纬度或经度将地图分为两张单独的地图

问题描述

有没有一种方法可以将ggplot2地图切成两个单独的地图?我有一张带有无法辨认的ID标签的大地图。我想将地图垂直分成两个不同的地图,最好有一个重叠的区域,以便每个多边形在至少一张地图中完整显示

这是一个可复制的示例。我想将地图分成北向35度的北区,然后再分成北35.5度的南区(两者都重叠)。 (虽然我意识到使用此示例进行其他拆分可能更有意义,但我的实际地图在垂直方向上较长。)

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. this post之后,我首先利用st_crop按纬度划分sf df并提取南部和北部地区的FIPS代码。
  2. 然后使用FIPS代码将sf数据帧分为两部分,以确保在两幅图中总共显示分界线上的区域。
  3. 最后,我添加一个ID并将两个df重新绑定在一起,以便使用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,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()