如何在R中创建邮政编码边界

时间:2018-07-06 13:14:31

标签: r dictionary zip boundary

我正在尝试创建一个名称为“社区”的地图,其中显示了多个邮政编码的边界。我拥有的数据与下面类似。变量是社区的名称,数字是相应的邮政编码。

Tooele       <- c('84074','84029')
NEUtahCo     <- c('84003', '84004', '84042', '84062')
NWUtahCounty <- c('84005','84013','84043','84045')

我能够绘制想要使用的整个区域的地图

ggmap(get_map(location = c(lon=-111.9, lat= 40.7), zoom = 9))

随附的是我想要的图片。

Map of Wasatch Front Communities

1 个答案:

答案 0 :(得分:3)

已经弄清了shapefile以及它与您要显示的zip的匹配方式,您已经有了一个不错的基础。简单的功能(sf)变得非常简单,全新的ggplot2 v3.0.0也具有geom_sf来绘制sf对象。

我不确定您所拥有的不同区域(县?)的名称是否重要,因此我将它们全部拼凑成小块,并将其捆绑为一个小块utah_zipstigris还添加了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...

然后,您可以仅针对所需的zip过滤sf -由于还有其他信息(县名),因此您可以使用联接将所有内容收集到一个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中的刻度。 / p>

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的边界框,然后使用该边界框获取底图。