Mir*_*iam 5 zip dictionary r boundary
我正在尝试创建一个具有“社区”名称的地图,该地图显示了多个邮政编码的边界。我拥有的数据与下面类似。其中变量是社区的名称,数字是相应的邮政编码。
Tooele <- c('84074','84029')
NEUtahCo <- c('84003', '84004', '84042', '84062')
NWUtahCounty <- c('84005','84013','84043','84045')
Run Code Online (Sandbox Code Playgroud)
我能够绘制要使用的整个区域的地图
ggmap(get_map(location = c(lon=-111.9, lat= 40.7), zoom = 9))
Run Code Online (Sandbox Code Playgroud)
附件是我想要的照片。
通过弄清楚shapefile及其与您要显示的zip的匹配方式,您已经为这奠定了不错的基础。简单的功能(sf)使得此操作非常容易,全新的ggplot2v3.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...
Run Code Online (Sandbox Code Playgroud)
然后,您可以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...
Run Code Online (Sandbox Code Playgroud)
您已经弄清楚了底图,并且由于ggmap制作了ggplot对象,因此只需添加一个geom_sf图层即可。这些技巧只是为了确保您声明要使用的数据,将其设置为不继承aes ggmap,然后关闭中的刻度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")
Run Code Online (Sandbox Code Playgroud)

您可能要调整底图的位置,因为它会切断其中一个拉链。一种方法是使用st_bbox获取的边界框utah_sf,然后使用来获取底图。