PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, June 27, 2022

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

 June 27, 2022     graph, plot, r     No comments   

Issue

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 should to be shaded in blue,
  • vec2 in red and
  • vec3 in green.
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?


Solution

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



Answered By - stefan
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing