Mathica
Mathica

Reputation: 1303

How to shade or fill counties with different colors on US map?

I have three vectors containing some county FIP codes.

Following this post I was able to shade counties on a map for each vector separately.

How can I shade counties from all three vectors on the same map?

vec1 <- c(4013, 6037, 17031, 26163, 36059)
vec2 <- c(48045, 1009)
vec3 <- c(48289, 48291)

dt <- countypop %>%
  dplyr::mutate(
    selected = factor(
      ifelse(fips %in% stringr::str_pad(vec1, 5, pad = "0"), "1", "0")
    )
  )

usmap::plot_usmap(data = dt, values = "selected", color = "grey") +
  ggplot2::scale_fill_manual(values = c("blue", "light gray"))

PS: Why doesn't par(mfrow=c(3,1)) give me a plot with three distinctive maps?

Upvotes: 1

Views: 1057

Answers (1)

stefan
stefan

Reputation: 125727

Basically it's the same approach but instead of making use of an ifelse you could make use of case_when to assign color to your county groups:

library(ggplot2)
library(usmap)
library(dplyr)
library(stringr)

dt <- countypop %>%
  mutate(fill = case_when(
    fips %in% str_pad(vec1, 5, pad = "0") ~ "Blue",
    fips %in% str_pad(vec2, 5, pad = "0") ~ "Red",
    fips %in% str_pad(vec3, 5, pad = "0") ~ "Green",
    TRUE ~ "Other"
  ))

plot_usmap(regions = "counties", data = dt, values = "fill", color = "grey") +
  scale_fill_manual(
    values = c(Blue = "blue", Green = "green", Red = "red", Other = "light gray")
  )

enter image description here

Upvotes: 1

Related Questions