# Section 3.4 script

# adopter-level installer data cannot be shared
# this script includes code to replicate figures 9-10

source("prep.R")

# set working directory to the data repositor
### setwd("YOUR WD")

# Figure 9
f9<-read.csv("Data/figure9.csv")
fgr<-function(mm,ttl,yL,yM) {
  fga<-filter(f9,stat==mm) %>% mutate(lo=ifelse(fl<H,fl,H),hi=ifelse(fl>H,fl,H))
  a<-base(fga)+ggtitle(ttl)+coord_cartesian(ylim=c(0,yM))+
    geom_ribbon(aes(x=year,ymin=lo,ymax=hi,fill=fnc),alpha=0.6)+
    geom_line(aes(year,fl,color=fnc))+
    geom_line(aes(year,H,color=fnc),linetype='dashed')+
    scale_color_manual(values=c('darkcyan','navy','tan1'),guide="none")+
    scale_fill_manual(values=c('darkcyan','navy','tan1'),guide="none")+
    #scale_shape_manual(values=c(16:18),guide="none")+
    ylab(yL)+theme(axis.title.x=element_blank())
  return(a)
}

# plot 
ggsave("Figures/figure9.jpg",
       plot=plot_grid(fgr("installer size","a) Average Installer Size","N\n(x1000)",40)+
                        ant("TPO",2019,20,4.5,'firebrick4')+ant("Loan",2022,12,4.5,'navy')+
                        ant("Customer financed",2019,2,4,'darkcyan')+
                        geom_segment(x=2017,xend=2017.8,y=38,yend=38,color='gray50')+ant("Full sample",2019.1,38,4,'gray50')+
                        geom_segment(x=2017,xend=2017.8,y=35,yend=35,color='gray50',linetype="dashed")+ant("High confidence",2019.55,35,4,'gray50'),
                      fgr("new installers","b) New Installer Share","   %   ",4)+
                        coord_cartesian(xlim=c(2017,2024)),
                      fgr("top 10 share","c) Top 10 Installer Share","   %  ",80),
                      fgr("hhi","d) Market Concentration (HHI)","HHI",0.26)+
                        scale_y_continuous(breaks=c(0,0.13,0.26),labels=c("0","0.13","0.26")),nrow=2),width=8,height=8)


# Figure 10
f10<-read.csv("Data/figure10.csv")
ggsave("Figures/figure10.jpg",
       plot=base(f10)+
         geom_ribbon(aes(x=year,ymin=lo,ymax=hi,fill=fnc),alpha=0.6)+
         geom_line(aes(year,storage,color=fnc))+
         geom_line(aes(year,hc,color=fnc),linetype='dashed')+
         scale_color_manual(values=c('darkcyan','navy','tan1'),guide="none")+
         scale_fill_manual(values=c('darkcyan','navy','tan1'),guide="none")+
         ylab("Storage\nAttachment\nRate\n(%)")+theme(axis.title.x=element_blank())+
         ant("TPO",2023,30,5,'firebrick4')+ant("Loan",2018,6,5,'navy')+
         ant("Customer financed",2022.5,2.5,5,'darkcyan'),width=5,height=5)


