MetricT

NICS Firearm Background Checks by Month

Aug 22nd, 2020
342
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 2.30 KB | None | 0 0
  1. ### My remix of the "NICS Firearm Background Checks" thread - /u/MetricT
  2. ### https://www.reddit.com/r/dataisbeautiful/comments/ie4wxu/fbi_firearm_background_checks_over_time_oc/
  3. ###
  4. ### First, you need to convert the data from this pdf into something useable:
  5. ###
  6. ###   https://www.fbi.gov/file-repository/nics_firearm_checks_-_month_year.pdf/view
  7. ###
  8. ### I used Tabula [https://tabula.technology/] to scan the PDF and save it as a spreadsheet
  9. ### If you do this, export it as "stream" instead of the default "lattice" to get it in the
  10. ### correct form.  
  11. ###
  12. ### Fire up the .csv Tabula made in Excel and trim off the "Total" column, although strictly
  13. ### speaking it wasn't necessary.
  14. ###
  15. ### At this point, R should handle the rest...
  16. ###
  17. ### The "geom_inauguration_dates" is a function I wrote.  I haven't published it yet because
  18. ### it's not a true geom_* object, it just uses a similar function call.  If anyone wants to
  19. ### help me turn it into an actual geom_ object, hit me up...
  20.  
  21. data <-
  22.   "NICS_Firearm_Background_Checks.csv" %>%
  23.   read_csv(col_names = TRUE, col_types = "dnnnnnnnnnnnn") %>%
  24.   pivot_longer(-Year, names_to = "Month", values_to = "NICS_Firearm_Background_Checks") %>%
  25.   filter(!is.na(NICS_Firearm_Background_Checks)) %>%
  26.   filter(Year >= 1999) %>%
  27.   mutate(yearmonth = yearmonth(paste(Year, " ", Month))) %>%
  28.   select(yearmonth, NICS_Firearm_Background_Checks)
  29.  
  30. model <-
  31.   data %>%
  32.   as_tsibble(index = "yearmonth") %>%
  33.   model(STL(NICS_Firearm_Background_Checks ~ trend(window = 90))) %>%
  34.   components()
  35.  
  36. graph <-
  37.   model %>%
  38.   select(yearmonth, NICS_Firearm_Background_Checks, trend, season_adjust) %>%
  39.   rename(values = NICS_Firearm_Background_Checks) %>%
  40.   filter(yearmonth >= yearmonth("1999 Jan")) %>%
  41.   ggplot(aes(x = yearmonth(yearmonth))) +
  42.   geom_point(aes(y = values), alpha = 0.2) +
  43.   geom_line(aes(y = trend * 0.85), size = 0.8, linetype = "dotted", color = "black") +
  44.   geom_line(aes(y = season_adjust), size = 1.2, color = "darkseagreen4") +
  45.   labs(x = "Date",
  46.        y = "# of Background Checks",
  47.        title = "NICS Firearm Background Checks by Month") +
  48.   scale_y_continuous(labels = scales::comma) +
  49.   theme_bw() +
  50.   geom_inauguration_dates(min(model$yearmonth), max(model$yearmonth), 3500000) +  
  51.   theme(legend.position = "none")
  52. print(graph)
Add Comment
Please, Sign In to add comment