Advertisement
binkleym

US Unemployment + Doppler Map

Jan 9th, 2020
403
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 4.65 KB | None | 0 0
  1. ### Render a map of US unemployment by state, and a "Doppler map" showing
  2. ### how quickly unemployment is falling/growing
  3.  
  4. ### You need a FRED API key in order to pull data from FRED.
  5. ### You may request an API key at:
  6. ### https://research.stlouisfed.org/useraccount/apikeys
  7. api_key_fred   <- "INSERT_YOUR_FRED_API_KEY_HERE"
  8.  
  9. ### We need the following packages for this example.
  10. packages <- c("tidyverse", "lubridate", "fredr", "ggplot2", "maps", "sf",
  11.               "ggthemes", "tsibble", "dplyr", "broom", "ggfortify",
  12.               "usmap", "forecast", "gridExtra", "cartogram", "RColorBrewer")
  13.  
  14. ### Install packages if needed, then load them quietly
  15. new_packages <- packages[!(packages %in% installed.packages()[, "Package"])]
  16. if (length(new_packages)) install.packages(new_packages, quiet = TRUE)
  17. invisible(lapply(packages, "library", quietly = TRUE,
  18.                  character.only = TRUE, warn.conflicts = FALSE))
  19.  
  20. ### Now set the FRED API key
  21. fredr_set_key(api_key_fred)
  22.  
  23. ### We need several years worth of data in order to filter out
  24. ### the seasonal component.  Ten years is a nice round number...
  25. date_start <- as.Date("2010-01-01")
  26. date_end   <- as.Date(now())
  27.  
  28. ### Create an empty tibble to hold our data
  29. trend_unemployment <- tibble(state        = character(),
  30.                              unemployment = numeric(),
  31.                              velocity     = numeric())
  32.  
  33. for (state in state.abb) {
  34.  
  35.   # Pull data from FRED
  36.   data <- fredr(series_id = paste(state, "URN", sep = ""),
  37.                 observation_start = date_start,
  38.                 observation_end   = date_end,
  39.                 frequency = "m")
  40.  
  41.   date   <- data %>% as_tsibble(index = "date") %>% pull("date")
  42.   values <- data %>% as_tsibble(index = "date") %>% pull("value")
  43.  
  44.   # Decompose the data and pluck out the trend component
  45.   trend <- values %>%
  46.            ts(frequency = 12, start = c(year(min(date)), month(min(date)))) %>%
  47.            mstl() %>%
  48.            trendcycle()
  49.  
  50.   # Compute the 6 month average of unemployment
  51.   unemployment <- trend %>% tail(n = 6) %>% mean()
  52.  
  53.   # Compute the 6 month average of unemployment velocity
  54.   velocity <- trend %>% diff() %>% tail(n = 6) %>% mean()
  55.  
  56.   # Append result to our tibble
  57.   trend_unemployment <- trend_unemployment %>%
  58.                         add_row(state, unemployment, velocity)
  59.  
  60. }
  61.  
  62. ### use the "state.name" and "state.abb" databases to convert two-letter state
  63. ### codes to lowercase names (tennnessee, california, etc).   Add the resulting
  64. ### lowercase name to the tibble
  65. match <- match(trend_unemployment$state, state.abb)
  66. trend_unemployment$state_name <- state.name[match] %>% tolower()
  67.  
  68. ### Load a map of states in the USA.   The maps have a list of lowercase
  69. ### state names, which will use to match against "pres" down below
  70. us_map <- maps::map("state", plot = FALSE, fill = TRUE)
  71.  
  72. ### Change the latitude/longitude data to a simple feature object
  73. us_map <- sf::st_as_sf(us_map)
  74.  
  75. ### Change the name of the "ID" column to "state_name"
  76. names(us_map) <- c("geometry", "state_name")
  77.  
  78. ### Remove the District of Colombia from our map
  79. us_map <- us_map %>% filter(state_name != "district of columbia")
  80.  
  81. ### Add our velocity data to the map data
  82. us_map <- us_map %>% left_join(trend_unemployment, by = "state_name")
  83.  
  84. ### Map the unemployment data
  85. my_palette <- rev(brewer.pal(9, "Blues"))
  86. p1 <- ggplot(us_map, aes(fill = unemployment), col = "black") +
  87.  
  88.       # Title of our graph
  89.       labs(title = "Trend Unemployment by State, 6 month average") +
  90.  
  91.       # Draw our map
  92.       geom_sf() +
  93.  
  94.       # Change the map projection to make it look nicer
  95.       coord_sf(crs = "+proj=aea +lat_1=25 +lat_2=50 +lon_0=-100", ndiscr = 0) +
  96.  
  97.       # Use "heat" colors to color the map by unemployment
  98.       scale_fill_gradientn(name = "Unemployment",
  99.                            colours = my_palette,
  100.                            trans = "log10") +
  101.       theme_void()
  102.  
  103. p2 <- ggplot(us_map, col = "black") +
  104.  
  105.       # Title of our graph
  106.       labs(title = "Trend Unemployment Change by State, 6 month average") +
  107.  
  108.       # Color states using green for falling unemployment, red for rising
  109.       # unemployment
  110.       geom_sf(aes(fill = velocity)) +
  111.       scale_fill_gradient2(name = "Unemployment",
  112.                            low  = "palegreen4",
  113.                            mid  = "white",
  114.                            high = "firebrick2") +
  115.  
  116.       # Change the map projection to make it look nicer
  117.       coord_sf(crs = "+proj=aea +lat_1=25 +lat_2=50 +lon_0=-100", ndiscr = 0) +
  118.  
  119.       # Disable theming
  120.       theme_void()
  121.  
  122. ### Combine the two graphs
  123. grid.arrange(p1, p2, nrow = 2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement