Advertisement
binkleym

US Unemployment + Doppler Map

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