##################################################
################ PREPARATION #####################
##################################################
# Clear environment
rm(list=setdiff(ls(), "path_to"))

# Load data
gcd = readRDS(path_to("gcd")) %>% filter(treatment == 0)
world = readRDS(path_to("world"))


##################################################
################ PLOT ############################
##################################################
# Global averages
df = data.frame(
  x = c("actual", "belief"),
  y = c(
    wtd.mean(gcd$coop, weights=gcd$wgt_expctrl_pop15, na.rm=T),
    wtd.mean(gcd$coop_belief, weights=gcd$wgt_expctrl_pop15, na.rm=T)
  )
)
df$label = paste0(round(df$y*100), "%")


plots = subplots = list()
p1 = ggplot(df, aes(x=x, y=y)) +
  geom_bar(stat="identity", fill="#90353b") +
  geom_text(aes(label=label, y=y+0.03), size=3.5) +
  scale_x_discrete(labels=c("Actual", "Expected")) +
  scale_y_continuous(breaks=seq(0,1,0.1), labels=paste0(seq(0,1,0.1)*100, "%")) +
  coord_cartesian(ylim=c(0,1)) +
  xlab("Cooperation rate") + ylab("Global means") +
  ggtitle("A: Global means") +
  theme_minimal() + theme(
    plot.title = element_text(size=15, face="bold", hjust=0.5),
    axis.title = element_text(face="bold", size=12),
    axis.text = element_text(size=10),
    panel.grid.major.x = element_blank(),
    panel.grid.minor = element_blank(),
    legend.direction="none"
  )

cor = round(cor(world$gcd_coop_wgtexpctrl, world$gcd_coop_belief_wgtexpctrl, use="complete.obs"), 2)
pval = cor.test(world$gcd_coop_wgtexpctrl, world$gcd_coop_belief_wgtexpctrl, use="complete.obs")$p.value
p2 = ggplot(world, aes(x=gcd_coop_belief_wgtexpctrl, y=gcd_coop_wgtexpctrl)) +
  geom_abline(slope = 1, intercept = 0, color = "black", linetype = "dashed", size=.6) +
  geom_point() +
  annotate("text", x = 0.8, y = 0.4, label = paste0("ρ = ", cor, "***"), parse = F, size = 5) +
  geom_smooth(method="lm", se=F, color="#90353b", size=1, fullrange=T) +
  coord_cartesian(xlim=c(0.25, .95), ylim= c(0.25, .95)) +
  scale_y_continuous(breaks=seq(0.3,0.95,0.2), labels=paste0(seq(0.3,0.95,0.2)*100, "%")) +
  scale_x_continuous(breaks=seq(0.3,0.95,0.2), labels=paste0(seq(0.3,0.95,0.2)*100, "%")) +
  xlab("Expected cooperation rate") +
  ylab("Actual cooperation rate") +
  ggtitle("B: Scatterplot of country means") +
  theme_minimal() + theme(
    plot.title = element_text(size=15, face="bold", hjust=0.5),
    axis.title = element_text(face="bold", size=12),
    axis.text = element_text(size=10),
    panel.grid.minor = element_blank(),
    legend.direction="none"
  )

plots$fig_3 = p1 + p2 + 
  plot_layout(widths = c(1, 2))


#### EXPORT ####
n = "fig_3"
pdf(paste0(path_to("figures"), n, ".pdf"), width = 6, height = 4)
print(plots[[n]])
dev.off()  
