bcallaway11 / did

Difference in Differences with Multiple Periods, website: https://bcallaway11.github.io/did
288 stars 92 forks source link

Changing group names in ggdid() output? #85

Closed sjoerdvanalten closed 2 years ago

sjoerdvanalten commented 2 years ago

Dear Callaway and Sant'Anna,

Thanks for the great paper and this very user-friendly R-package.

The example in the Readme plots the group-ATTs using ggdid(out, ylim = c(-.25,.1))

Is there any way to change the name of the groups from the year of treatment into something else in the plot? For example, what if I would like to call "Group 2004'', "First treated group'' in the plot, "Group 2006'', "Second treated group'', etc?

bcallaway11 commented 2 years ago

I think it might be easier to do this just by creating your own plot from the output of att_gt. For example, the following code generates something that (I think) is close to what you are talking about here.

library(did)
library(ggplot2)
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
data(mpdta)

out <- att_gt(yname = "lemp",
              gname = "first.treat",
              idname = "countyreal",
              tname = "year",
              xformla = ~1,
              data = mpdta,
              est_method = "reg"
)

plotdf <- cbind.data.frame(group=out$group, 
                           time.period=out$t, 
                           att=out$att, 
                           se=out$se, 
                           crit.val=out$c,
                           row.names=NULL)

plotdf$post <- as.factor(1*(plotdf$group >= plotdf$time.period))

# create custom group names
plotdf$group_name <- case_when(plotdf$group==2004 ~ "First treated group",
                               plotdf$group==2006 ~ "Second treated group",
                               plotdf$group==2007 ~ "Third treated group")

ggplot(plotdf, aes(x=time.period, y=att, color=post)) +
  geom_point() +
  geom_errorbar(aes(ymax=(att+crit.val*se), 
                    ymin=(att-crit.val*se)),
                width=.1) + 
  facet_wrap(~group_name, ncol=1) +
  theme_bw()