Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Code for figures displaying annual number of fatal automobile crashes, fatalities, etc. in Austin and Travis County, 2003-2015
library(tidyr)
library(dplyr)
library(stringr)
library(ggplot2)
#--------------------------------
# format the data for graphing
#--------------------------------
crash_dat <- read.csv("http://blogs.edb.utexas.edu/pusto/files/2015/08/Yearly_crash_data_Austin_and_Travis_County.csv")
select(crash_dat, Year, Locale, srce, Fatal_crashes:Incapacitating_injuries, Total_crashes) %>%
mutate(Fatality_rate = Fatal_crashes / Total_crashes) %>%
gather("quantity","n", Fatal_crashes:Total_crashes, Fatality_rate) %>%
filter(!is.na(n) & (srce=="CRIS" | Year < 2010)) %>%
mutate(partial = (Year==2015),
quantity = str_replace(quantity,"_"," "),
projection = "actual") ->
crashes
#-------------------------------
# Total crashes figure
#-------------------------------
filter(crashes, Year==2015, quantity != "Fatality rate") %>%
mutate(n = 0, Year=2003) ->
crashes_axis
filter(crashes, Year==2015, quantity != "Fatality rate") %>%
mutate(n = n * 12 / 7, projection = "projected") ->
crashes_projected
crashes <- rbind(crashes, crashes_projected)
filter(crashes, quantity != "Fatality rate") %>% droplevels() %>%
ggplot(aes(Year, n, color = Locale, shape = projection,
group = interaction(Locale, projection, partial))) +
geom_line() + geom_point() +
geom_blank(data = crashes_axis) +
geom_smooth(method = "lm", se = FALSE, linetype = "dashed") +
scale_color_brewer(type = "qual", palette=7) +
scale_x_continuous(breaks = 2003:2015, labels = c(2003:2014, "2015 \n (Through 7/31)")) +
facet_wrap(~ quantity, ncol = 1, scales = "free") +
theme_minimal() + theme(legend.position="bottom") +
labs(color = "", y = "Total", shape = "",
title = "Annual crashes and fatalities/injuries \n Austin and Travis County (2003-2015)")
#-------------------------------
# Fatality rate figure
#-------------------------------
fatality_rate <- filter(crashes, quantity=="Fatality rate")
ggplot(fatality_rate, aes(Year, n, color = Locale, group = interaction(Locale, partial))) +
geom_line() + geom_point() +
scale_color_brewer(type = "qual", palette=7) +
scale_y_continuous(limits = c(0,.01)) +
scale_x_continuous(breaks = 2003:2015, labels = c(2003:2014, "2015 \n (Through 7/31)")) +
theme_minimal() + theme(legend.position="bottom") +
labs(color = "", y = "Fatal crashes / Total crashes",
title = "Proportion of crashes that are fatal \n Austin and Travis County (2003-2015)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.