Home > Blockchain >  how to plot specific US counties using their FIP with a gradient effect on single map
how to plot specific US counties using their FIP with a gradient effect on single map

Time:10-05

I have dataframe below:

mydf <- data.frame(FIP=c(1017,1059,1061,1133,5103,12129,13123,12129), 
val=c(100,100,225,400,180,278,180,321))

I want to shade US counties on one single map whose FIPs are in FIP colum, but I am stuck at is how to shade these specific counties such that something like a heat map appears. the counties higher pop are more red and counties with lower pop are more blue (like typical gradient of heat map).

library(tidyverse)
library(usmap)
library(grDevices)


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

usmap::plot_usmap(data = dt, values = "selected", color = "grey")  
    ggplot2::scale_fill_manual(values = c(rainbow(8))

I can shade specific counties (although if all are going to be shaded with color!) but I want a gradient effect here.

CodePudding user response:

Maybe this is what you are looking for. As far as I get it you want to make a map where only the counties present in your dataframe df get colored according to the val.

To this end you could join mydf to countypop. Doing so will automatically assign NA to the val column of non-selected counties. To color by val you have to set the values argument equal to "val" in usmap::plot_usmap. To get a gradient of values use ggplot2::scale_fill_gradient where you could set the color used for NA via the na.value argument, e.g. in the code below I make use of na.value = "transparent":

mydf <- mutate(mydf, FIP = stringr::str_pad(FIP, 5, pad = "0"))

dt <- countypop %>%
  left_join(mydf, by = c("fips" = "FIP"))

usmap::plot_usmap(data = dt, values = "val", color = "grey", size = .25)  
  ggplot2::scale_fill_gradient(low = "blue", high = "red", na.value = "transparent")

enter image description here

  • Related