Reputation: 213
I am looking to fill in counties on a ggplot2 US map from a vector of FIPS codes that I am interested in. I would like to do this using ggplot2 and its various functions such as geom_map and geom_polygon as they seem to offer quite a lot of flexibility in customisation, however I have only managed to accomplish a rudimentary version using choropleth. The rudimentary version is:
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()
which gives this. Here OOTFIPS is a vector of the FIPS codes. To make this work, I have had to create a fake "value" vector so that it will highlight the counties desired from the OOTFIPS vector.
Starting with ggplot2, when I make a first pass I cant even get an accurate map. I have started with this code
counties <- map_data("county")
ggplot() + geom_polygon(data = counties, aes(x = long, y = lat))
but it returns a map that isn't even geographically accurate. Any advice on how to make a map similar to the first image but with the techniques from the second?
Thanks!
ExampleFIPS <- data.frame("FIPS" = c(19097, 17155, 50009, 27055, 39143, 55113, 44003, 55011, 19105, 46109, 19179, 55099, 51057))
Edit: Here is as far as I have been able to manage
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)
But now the question is how to specify and highlight counties with FIPS codes in the vector?
Upvotes: 3
Views: 2739
Reputation: 2724
I'd call this a straight forward example of data wrangling.. you need to find where all your needed data is. That is, map_data("county")
is missing the fips, then you need to google where to find it - maps::county.fips
, check the format, create a data frame from it and then join it in and use it.
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"))
Upvotes: 3