Fatalities Difference in Differences Visual

mail@pastecode.io avatar
unknown
r
2 years ago
1.1 kB
2
Indexable
Never
library(tidyverse)
library(gganimate)
library(foreign)

# Get summary data for group averages
USFatalities_DiD %>% 
  group_by(year,treat) %>% 
  summarize(y=mean(fatal_rate)) -> sumdata

# Plot

ggplot() + geom_line(data=USFatalities_DiD,aes(x=year,y=fatal_rate,group=state,color=as.factor(treat)),
                     size=1,alpha=0.25) + # plot the individual lines
  geom_line(data=sumdata,aes(x=year,y=y,group=treat,color=as.factor(treat)),
            size=2) + # plot the averages for each group
  geom_vline(xintercept=1986) + # intervention point
  scale_x_continuous(breaks=unique(USFatalities_DiD$year)) +
  scale_color_manual(values=c("red","blue"), # label our groups
                     labels=c("Control Average (no tax increase)","Treatment Average (tax increase)")) +
  labs(title="Difference in Differences Visual in R",
       subtitle="Using ggplot2",
       x="Year",
       y="Fatal_rate") +
  theme_minimal() +
  theme(legend.title = element_blank(),
        legend.position = "bottom") +
        ylim(1.5,2.5) # Limit y-axis for better readability