MetricT

Car crashes in Nashville by Hour and Day

Jul 29th, 2020 (edited)
473
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 1.94 KB | None | 0 0
  1. ### Construct a map of traffic accident date vs time similar to:
  2. ### https://www.reddit.com/r/dataisbeautiful/comments/i0a91n/car_crashes_by_time_and_day_chicago_oc/
  3. ### Data Source:  https://data.nashville.gov/browse?category=Public%20Safety
  4.  
  5. library(tidyverse)
  6. library(janitor)
  7. library(lubridate)
  8.  
  9. data <-
  10.   "Nashville/Traffic_Accidents/Traffic_Accidents__2020_.csv" %>%
  11.   read_csv() %>%
  12.   janitor::clean_names()
  13.   select(date_and_time) %>%
  14.   filter(!is.na(date_and_time)) %>%
  15.   mutate(date_and_time = mdy_hms(date_and_time)) %>%
  16.   mutate(hour   = hour(date_and_time)) %>%
  17.   mutate(dow    = wday(date_and_time)) %>%
  18.   group_by(hour, dow) %>%
  19.   summarize(wrecks = n())
  20.  
  21. g_wrecks_hour_dow <-
  22.   ggplot(data = data, aes(x = hour, y = dow, fill = wrecks)) +
  23.   theme_minimal() +
  24.   theme(legend.position = "none") +
  25.   theme(plot.title = element_text(hjust = 0.5)) +
  26.   theme(plot.subtitle = element_text(hjust = 0.5)) +
  27.   theme(plot.caption = element_text(hjust = 0.5)) +
  28.   geom_tile(color = "white") +
  29.  
  30.   labs(title = "Car Crashes by Time of Week in Nashville",
  31.        subtitle = "Relative Frequency of Reported Crashes by Day, Hour",
  32.        caption = paste("Data source:  https://data.nashville.gov/browse?category=Public%20Safety\n",
  33.                        "Inspired by:   https://www.reddit.com/r/dataisbeautiful/comments/i0a91n/car_crashes_by_time_and_day_chicago_oc/",
  34.                        sep = ""),
  35.        x = "", y = "") +
  36.  
  37.   scale_fill_gradient(low = "white", high = "darkred") +
  38.  
  39.   scale_y_continuous(trans = "reverse",
  40.                      breaks = c(1, 2, 3, 4, 5, 6, 7),
  41.                      labels = c("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")) +
  42.  
  43.   scale_x_continuous(breaks = c(0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22),
  44.                      labels = c("12 am", "2 am", "4 am", "6 am", "8 am", "10 am", "12 pm", "2 pm ", "4 pm", "6 pm", "8 pm", "10 pm"))
  45.  
  46. print(g_wrecks_hour_dow)
Add Comment
Please, Sign In to add comment