使用ggplot2根据FIPS代码填写郡县

时间:2019-05-04 12:11:06

标签: r ggplot2 choropleth

我希望从我感兴趣的FIPS代码向量中填充ggplot2美国地图上的县。我想使用ggplot2及其各种功能(例如geom_map和geom_polygon)来完成此任务,因为它们似乎提供了相当多的功能在定制方面有很大的灵活性,但是我只能使用choropleth来完成基本版本。基本版本是:

library(choroplethr)
library(ggplot2)
library(dplyr)
library(tidyverse)
library(choroplethrMaps)

onesvec <- rep(100000, 210)
county <- data.frame(region = OOTFIPS, value = onesvec)

data(county)

choro              = CountyChoropleth$new(county)
choro$ggplot_scale = scale_fill_brewer(name="Population", palette=2, drop=FALSE)
choro$render() 

给出this。 OOTFIPS是FIPS代码的向量。为了使这项工作有效,我必须创建一个伪造的“值”向量,以便突出显示OOTFIPS向量中所需的县。

从ggplot2开始,当我第一次通过时,我什至无法获得准确的地图。我已经从这段代码开始

counties <- map_data("county")
ggplot() + geom_polygon(data = counties, aes(x = long, y = lat))

,但它返回的映射甚至不是geographically accurate。关于如何制作与第一张图片相似但使用第二张图片类似技术的地图的任何建议?

谢谢!

ExampleFIPS <- data.frame("FIPS" = c(19097, 17155, 50009, 27055, 39143, 55113, 44003, 55011, 19105, 46109, 19179, 55099, 51057))

编辑:据我所能完成的

states <- map_data("state")
counties <- map_data("county")

us_base <- ggplot(data = states, mapping = aes(x = long, y = lat, group = group)) + coord_fixed(1.3) + 
  geom_polygon(color = "black", fill = "white")


us_base + theme_void() + geom_polygon(data = counties, fill = NA, color = "gray") +
  geom_polygon(color = "black", fill = NA)

但是现在的问题是如何在向量中使用FIPS代码指定和突出显示郡县?

1 个答案:

答案 0 :(得分:1)

我将这称为数据整理的直接示例。您需要找到所有所需数据的位置。也就是说,map_data("county")缺少这些缺陷,然后您需要在Google上找到它的位置-maps::county.fips,检查格式,从中创建数据框,然后将其加入并使用它。

library(tidyverse)

ExampleFIPS <- c(19097, 17155, 50009, 27055, 39143, 55113, 44003, 55011, 19105, 46109, 19179, 55099, 51057)

maps::county.fips %>%
  as.tibble %>% 
  extract(polyname, c("region", "subregion"), "^([^,]+),([^,]+)$") ->
  dfips

map_data("county") %>% 
  left_join(dfips) ->
  dall

dall %>% 
  mutate(is_example = fips %in% ExampleFIPS) %>% 
  ggplot(aes(long, lat, group = group)) +
  geom_polygon(aes(fill=is_example), color="gray70") +
  coord_map() +
  scale_fill_manual(values=c("TRUE"="red", "FALSE"="gray90"))

这产生 US counties with a few highlighted