# This code reproduces Figure 1 of
# Lehrer et al., 2024. 'Rallying Around the Leader in Times of Crises: The Opposing Effects of Perceived Threat and Anxiety'.
# European Journal of Political Research X(X): x-x.

library(viridis)
library(zoo)
library(tidyr)
library(tidyverse)
library(magrittr)

# load data
d <- readRDS("data_for_replication/polls_govparties.RDS")

# define vector of countries
countries <- unique(d$iso_code)

# function for last value in vector
last <- function(x) { return( x[length(x)] ) }

# plot
pdf(file = "figure1.pdf", width = 10, height=7.5)

par(cex=1.1)

# base for German case
plot(
  d$date_norm_cases[d$iso_code == "DEU"],
  d$voteshare_norm_smoothed[d$iso_code == "DEU"],
  type = "l",
  main = "",
  cex.main = 1,
  xlab = "Days before and after 7-day incidence first reached 7",
  ylab = "Change in approval (ppt)",
  xlim = c(-50, 120),
  ylim = c(-8, 17),
  xaxt='n',
  yaxt='n',
  col ="red4",
  lwd = 3,
  lty = "solid",
  las = 1,
  frame = T)

axis(side=1, at = seq(-50, 100, by=25))
axis(side=2, at = seq(-8, 16, by=4), las=2)

# other countries
for(i in countries[-c(5)]){
  lines(
    d$date_norm_cases[d$iso_code == i],
    d$voteshare_norm_smoothed[d$iso_code == i],
    col = "gray60",
    lwd = 1,
    lty = "solid")

}

lines(
  d$date_norm_cases[d$iso_code == "DEU"],
  d$voteshare_norm_smoothed[d$iso_code == "DEU"],
  col = "red4",
  lwd = 3,
  lty = "solid")

abline(
  v= 0,
  col = "black",
  lty = "dashed",
  lwd = 1)

lines(c(-55, 120),
      c(0,0),
      type = "l",
      lty = "longdash",
      lwd=1)

text(-2,
     15,
     "first day with\n7-day incidence of 7",
     cex=0.8,
     adj=1)


# add country labels
for(i in countries[-c(5, 18, 19, 4, 22)]){
  text(last(na.omit(d$date_norm_cases[d$iso_code == i]))+1,
       last(na.omit(d$voteshare_norm_smoothed[d$iso_code == i])),
       i,
       cex=0.7,
       col = "black",
       adj=0)
}

# extra loop for countries that would overlap with labels
for(i in countries[18]){
  text(last(na.omit(d$date_norm_cases[d$iso_code == i]))+2.3,
       last(na.omit(d$voteshare_norm_smoothed[d$iso_code == i])),
       i,
       cex=0.7,
       col = "black",
       adj=0)
}

for(i in countries[c(19, 22)]){
  text(last(na.omit(d$date_norm_cases[d$iso_code == i]))+1,
       last(na.omit(d$voteshare_norm_smoothed[d$iso_code == i]))-0.2,
       i,
       cex=0.7,
       col = "black",
       adj=0)
}

for(i in countries[4]){
  text(last(na.omit(d$date_norm_cases[d$iso_code == i]))+1,
       last(na.omit(d$voteshare_norm_smoothed[d$iso_code == i]))+0.3,
       i,
       cex=0.7,
       col = "black",
       adj=0)
}

text(last(na.omit(d$date_norm_cases[d$iso_code == "DEU"]))+1,
     last(na.omit(d$voteshare_norm_smoothed[d$iso_code == "DEU"])),
     "GER",
     cex=0.7,
     col = "red4",
     adj=0)

dev.off()

