# Star Wars at Central Banks Script - Drawing dissemination bias estimate charts
# Last Updated: 29 January 2021

library(tidyverse)
library(haven)
library(ggplot2)
source("Programs/E_paper-formatted_graphs/starwars_graph_theme.R") # ggplot theme for graphs

#Reshape necessary data
diss_bias_data <- read_dta("Data/Temp/export_from_r.dta") %>%
  select(xxx, yf_cb_real, yf_topJ_real, yf_cb_vhlss, 
         yf_topJ_vhlss, yf_cb_qog, yf_topJ_qog) %>%
  mutate_at(vars(-xxx), function(x) 100*x/x[196]) %>%
  pivot_longer(-xxx, names_to = "line_name") %>%
  mutate(sample_name = case_when(grepl("_cb_", line_name) == TRUE ~ "Central banks",
                                 TRUE ~ "Top journals"),
         line_name = gsub("_cb|_topJ", "", line_name)) %>%
  pivot_wider(names_from = sample_name, values_from = value) %>%
  mutate(line_name = factor(line_name, levels = c("yf_real", "yf_vhlss", "yf_qog"))) %>%
  rename(z_score = xxx) %>%
  pivot_longer(c(`Central banks`, `Top journals`), names_to = "sample")

#Draw Figure 7
facet_number <- 0 #this is necessary because of the hack way I have implemented custom breaks
label_number <- 0

Figure7 <- ggplot(data = diss_bias_data, aes(x = z_score)) +
  geom_line(aes(y = value, colour = sample, linetype = sample), size = 0.8) +
  facet_grid(cols = vars(line_name)) +
  theme_starwars() +
  geom_text(aes(label = groupings, x = 2, y = 142.5),
            data = after_scale(data.frame(line_name = unique(diss_bias_data[["line_name"]]), 
                              groupings = c("WDI used for P[z]", "VHLSS used for P[z]", 
                                            "QOG used for P[z]"))),
            size = 5.5) +
  ylab("Probability index, 100 at z = 1.96") +
  xlab("|z-score|") +
  scale_colour_manual(values = c("#00BA38", "#00BA38")) +
  scale_linetype_manual(values = c(1, 2)) +
  scale_y_continuous(expand = c(0, 0), limits = c(0, 150), 
                     sec.axis = sec_axis(~., name = "Probability index, 100 at z = 1.96")) +
  scale_x_continuous(expand = c(0, 0), limits = c(0, 4), breaks = z4_breaks, labels = z4_labels) +
  theme(axis.title.y = element_text(size = rel(1.5), angle = 90, vjust = 1, margin=unit(c(0,5,0,0), "mm")),
        axis.title.y.right = element_text(size = rel(1), angle = 90, vjust = 1, margin=unit(c(0,0,0,5), "mm")),
        legend.position = "bottom",
        legend.direction = "horizontal",
        legend.justification = c(0.5, 0))

#Save Figure 7
facet_number <- 0 #this is necessary because of the hack way I have implemented custom breaks
label_number <- 0
ggsave("Figures/RDP_Figure7.png", Figure7, device = agg_png, scaling = 1.3,
       units = "mm", width = 360, height = 171, dpi = 500)      


  
  