通过弄清楚 shapefile 以及它与您想要显示的 zip 的匹配方式,您已经为此奠定了良好的基础。简单的功能 (sf) 使这变得非常容易,全新的 ggplot2 v3.0.0 具有 geom_sf 来绘制 sf 对象。
我不确定您拥有的不同地区(县?)的名称是否重要,所以我只是将它们全部放入小标题中并将其绑定到一个标题中,utah_zips。 tigris 还添加了sf 支持,所以如果你设置class = "sf",你会得到一个sf 对象。为简单起见,我只是抽出您需要的列并简化其中一个名称。
library(tidyverse)
library(tigris)
library(ggmap)
Tooele <- c('84074','84029')
NEUtahCo <- c('84003', '84004', '84042', '84062')
NWUtahCounty <- c('84005','84013','84043','84045')
utah_zips <- bind_rows(
tibble(area = "Tooele", zip = Tooele),
tibble(area = "NEUtahCo", zip = NEUtahCo),
tibble(area = "NWUtahCounty", zip = NWUtahCounty)
)
zips_sf <- zctas(cb = T, starts_with = "84", class = "sf") %>%
select(zip = ZCTA5CE10, geometry)
head(zips_sf)
#> Simple feature collection with 6 features and 1 field
#> geometry type: MULTIPOLYGON
#> dimension: XY
#> bbox: xmin: -114.0504 ymin: 37.60461 xmax: -109.0485 ymax: 41.79228
#> epsg (SRID): 4269
#> proj4string: +proj=longlat +datum=NAD83 +no_defs
#> zip geometry
#> 37 84023 MULTIPOLYGON (((-109.5799 4...
#> 270 84631 MULTIPOLYGON (((-112.5315 3...
#> 271 84334 MULTIPOLYGON (((-112.1608 4...
#> 272 84714 MULTIPOLYGON (((-113.93 37....
#> 705 84728 MULTIPOLYGON (((-114.0495 3...
#> 706 84083 MULTIPOLYGON (((-114.0437 4...
然后,您可以过滤 sf 以获得您需要的 zip — 因为还有其他信息(县名),您可以使用连接将所有内容都放在一个 sf 数据框中:
utah_sf <- zips_sf %>%
inner_join(utah_zips, by = "zip")
head(utah_sf)
#> Simple feature collection with 6 features and 2 fields
#> geometry type: MULTIPOLYGON
#> dimension: XY
#> bbox: xmin: -113.1234 ymin: 40.21758 xmax: -111.5677 ymax: 40.87196
#> epsg (SRID): 4269
#> proj4string: +proj=longlat +datum=NAD83 +no_defs
#> zip area geometry
#> 1 84029 Tooele MULTIPOLYGON (((-112.6292 4...
#> 2 84003 NEUtahCo MULTIPOLYGON (((-111.8497 4...
#> 3 84074 Tooele MULTIPOLYGON (((-112.4191 4...
#> 4 84004 NEUtahCo MULTIPOLYGON (((-111.8223 4...
#> 5 84062 NEUtahCo MULTIPOLYGON (((-111.7734 4...
#> 6 84013 NWUtahCounty MULTIPOLYGON (((-112.1564 4...
您已经确定了底图,并且由于ggmap 生成了ggplot 对象,您只需添加geom_sf 图层即可。技巧只是确保您声明您正在使用的数据,将其设置为 not 从 ggmap 继承 aes,并关闭 coord_sf 中的刻度。
basemap <- get_map(location = c(lon=-111.9, lat= 40.7), zoom = 9)
ggmap(basemap) +
geom_sf(aes(fill = zip), data = utah_sf, inherit.aes = F, size = 0, alpha = 0.6) +
coord_sf(ndiscr = F) +
theme(legend.position = "none")
您可能需要调整底图的位置,因为它会切断其中一个拉链。一种方法是使用st_bbox 获取utah_sf 的边界框,然后使用它获取底图。