## ---------------------------
##
## Script name: Visualise data for 'Adult Aedes albopictus in winter: implications for mosquito surveillance in Southern Europe'
## Purpose of script: Plot graphs for the commentary
## Author: Daniela Lührsen
## Date Created: 2023-06-29
##
## Email: daniela.luhrsen@bsc.es
##
## ---------------------------

# load the packages
packages <- c("lubridate", "ggplot2", "dplyr", "patchwork", "ggrepel")
install.packages(setdiff(packages, rownames(installed.packages())))
lapply(packages, require, character.only = TRUE)

# load mean temperature data from elefsina
tmean <- read.csv(paste0("data/tmean_elefsina_1993-2023.csv"))

# convert from character to date-class and add different date formats
tmean$date <- as.Date(tmean$date)
tmean$month_year <- format(tmean$date, format = "%m-%Y")
tmean$day_month <- format(tmean$date, format = "%d-%m")

# plot figure A

# calculate the monthly mean temperature
monthly_data <- aggregate(list(temp = tmean$tmean),
  by = list(month = tmean$month_year),
  FUN = mean, na.rm = T
)

# set columns with date of the first of each month and year
monthly_data$month <- as.Date(paste0("01-", monthly_data$month), "%d-%m-%Y")
monthly_data$year <- as.numeric(year(monthly_data$month))
monthly_data <- monthly_data[order(monthly_data$month), ]

# calculate the mean of each month of the reference period (1993-2021)
mean_month <- aggregate(list(temp = monthly_data$temp[year(monthly_data$month) < 2022]),
  by = list(month = month(monthly_data$month[year(monthly_data$month) < 2022])),
  FUN = mean, na.rm = T
)

# calculate the anomaly for each month of the timeseries
monthly_data$mean <- mean_month$temp[match(month(monthly_data$month), mean_month$month)]
monthly_data$anom <- monthly_data$temp - monthly_data$mean

# add day of the year column (for x-axis in the plot)
monthly_data$month_number <- as.numeric(month(monthly_data$month))

# add rows with January of the following year to each group, in order to make the lines of the spiral connect
monthly_data <- rbind(
  monthly_data,
  data.frame(
    month = monthly_data$month[month(monthly_data$month) == 1] + 365,
    anom = c(monthly_data$anom[month(monthly_data$month) == 1][c(-1)], NA),
    temp = c(monthly_data$temp[month(monthly_data$month) == 1][c(-1)], NA),
    mean = c(monthly_data$mean[month(monthly_data$month) == 1][c(-1)], NA),
    month_number = rep(13, times = ceiling(nrow(monthly_data) / 12)),
    year = year(monthly_data$month[month(monthly_data$month) == 1])
  )
)

# create dataframe to visualize the "zero-anomalies"-line in the graph
mean_ring <- data.frame(
  month = seq(as.Date("2020-01-01"), as.Date("2021-01-02"), by = "1 month"),
  anom = rep(0, times = 13),
  month_number = seq(1, 13, 1),
  year = rep("2023", times = 13)
)

# create tibble to visualize the degrees of anomalies (equivalent to the y-grid)
temp_lines <- tibble(
  x = 7,
  y = seq(-3, 3, 1),
  labels = c("-3\u00B0C", "-2\u00B0C", "-1\u00B0C", "0\u00B0C", "1\u00B0C", "2\u00B0C", "3\u00B0C")
)

# create a tibble to display the names of the month
month_labels <- tibble(
  x = 1:12,
  labels = month.abb,
  y = 4
)

# plot figure a
plot_a <- monthly_data %>%
  ggplot(aes(x = month_number, y = anom, group = year, color = year)) + 
  geom_col(
    data = month_labels, aes(x = x + 0.5, y = 2.4), fill = "white",
    width = 1,
    inherit.aes = FALSE
  ) +
  geom_col(
    data = month_labels, aes(x = x + 0.5, y = -2), fill = "white",
    width = 1,
    inherit.aes = FALSE
  ) +
  geom_hline(yintercept = seq(-5, 3, by = 0.5), color = "#E5E5E5") + 
  geom_line(size = 0.5) + #
  geom_hline(yintercept = 0, color = "black", size = 0.6) + # 0º anomaly line
  geom_line(data = monthly_data[monthly_data$year == 2022, ], col = "#006ba4", size=1.3) + # 2022 line                                              
  geom_text_repel(aes(label = year), data = monthly_data[monthly_data$month == "2022-12-01", ], col = "#006ba4", nudge_x = -0.1, nudge_y = 0.5) + # 2022 label
  geom_label(
    data = temp_lines, aes(x = x, y = y, label = labels), # y axis
    color = "black", fill = "#72bcd4", size = 3.4, label.size = 0.2,
    inherit.aes = FALSE
  ) +
  geom_text(
    data = month_labels, aes(x = x, y = y, label = labels, parse = TRUE), # month labels
    inherit.aes = FALSE, color = "#4682B4",
    angle = c(0, 330, 300, 270, 240, 210, 180, 150, 120, 90, 60, 30)
  ) +
  scale_x_continuous(
    breaks = 1:12,
    labels = month.abb, expand = c(0, 0),
    sec.axis = dup_axis(name = NULL, labels = NULL)
  ) +
  scale_y_continuous(
    breaks = seq(-5, 5, 1),
    limits = c(-5, 5),
    sec.axis = dup_axis(name = NULL, labels = NULL)
  ) +
  scale_color_gradient(high = "#C85200", low = "#FFDAB7", breaks = seq(1993, 2022, 5)) +
  coord_cartesian(xlim = c(1, 12)) +
  coord_polar() +
  labs(
    x = NULL,
    y = NULL,
    color = "Year"
  ) +
  theme(
    panel.background = element_rect(fill = "white", linewidth = 1),
    plot.background = element_rect(fill = "white", color = "white"),
    panel.grid = element_blank(),
    axis.text.x = element_blank(),
    axis.text.y = element_blank(),
    axis.title.y = element_blank(),
    axis.ticks = element_blank(),
    axis.title = element_text(color = "black", size = 13),
    plot.title = element_text(color = "black", hjust = 0.5, vjust = -20, size = 14, face = "bold"),
    legend.title = element_text(color = "black", size = 8.5, vjust = 0.8, face = "bold"),
    legend.position = c(0.5, 0.065),
    legend.direction = "horizontal",
    legend.key.size = unit(1.4, "lines"),
    legend.background = element_rect(fill = "white"),
    legend.key.width = unit(1.5, "cm")
  )
plot_a

# plot figure B

#create a function that visualizes the temperature distribution along a timeseries
anomaly_percentils <- function(data, year, title, polar = FALSE, xbreaks = "1 month") {
  # add day of the year column (for x-axis in the plot)
  data$doy <- format(data$date, "%d-%m")

  # separate historical reference and study period
  hist <- data[year(data$date) < year, ]
  now <- data[year(data$date) == year, ]

  # calculate the percentils of the historic reference
  hist_q <- aggregate(list(tmean = hist$tmean),
    by = list(doy = hist$doy),
    FUN = "quantile", probs = c(2.5, 25, 50, 75, 97.5) / 100, na.rm = T
  )

  # clean the percentils dataframe
  hist_q <- do.call(data.frame, hist_q)
  hist_q$doy <- as.Date(paste0(hist_q$doy, "-2022"), "%d-%m-%Y")
  hist_q <- hist_q[order(hist_q$doy), ]

  # plotting
  ggplot(data = hist_q, aes(x = doy)) +
    geom_line(aes(y = tmean.2.5., color = "5%", group = 1), color = "grey") +
    geom_ribbon(aes(ymin = tmean.2.5., ymax = tmean.25., fill = "95% percentile")) +
    geom_line(aes(y = tmean.25., color = "25%"), color = "grey") +
    geom_ribbon(aes(ymin = tmean.25., ymax = tmean.75., fill = "50% percentile")) +
    geom_line(aes(y = tmean.50., color = "Historical median")) +
    geom_line(aes(y = tmean.75., color = "75%"), color = "grey") +
    geom_ribbon(aes(ymin = tmean.75., ymax = tmean.97.5.), fill = "#ffbc79") +
    geom_line(aes(y = tmean.97.5., color = "95%"), color = "grey") +
    geom_line(data = now, aes(x = date, y = tmean, group = 1, color = "2022")) +
    xlab("Time (days)") +
    ylab(expression(paste("Mean temperature (", degree, "C)"))) +
    scale_fill_manual(values = c("95% percentile" = "#ffbc79", "50% percentile" = "#fc7d0b")) +
    scale_color_manual(values = c("Historical median" = "#c85200", "2022" = "#006ba4")) +
    scale_x_date(date_breaks = xbreaks, date_labels = "%d %b") +
    theme_bw() +
    theme(
      rect = element_rect(fill = "transparent"), panel.border = element_blank(),
      panel.background = element_blank(),
      legend.position = "bottom",
      legend.text = element_text(size = 7),
      legend.key.size = unit(0.3, "cm")
    ) +
    labs(fill = "", colour = "") +
    if (polar == TRUE) {
      coord_polar()
    } +
    guides(color = guide_legend(label.wrap = 2))
}

# filter to obtain only the months of December
tmean_dec <- tmean[month(tmean$date) == 12, ]

# apply plotting function
plot_b <- anomaly_percentils(tmean_dec, 2022, polar = F, xbreaks = "7 days")

plot_b


# plot figure C


# filter for the reference period (before 2022)
tmean_hist <- tmean[year(tmean$date) < 2022, ]

# calculate the 97.5 percentile of the reference period
hist_q <- aggregate(list(tmean = tmean_hist$tmean),
  by = list(doy = tmean_hist$day_month),
  FUN = "quantile", probs = c(97.5) / 100, na.rm = T
)
hist_q <- do.call(data.frame, hist_q)

# add the 97.5 percentile and calculate the difference between the mean temperature for each day
tmean$p975 <- hist_q$tmean[match(tmean$day_month, hist_q$doy)]
tmean$anom <- tmean$tmean - tmean$p975

# if the difference is negative, set to 0
tmean$anom[tmean$anom < 0] <- 0

# aggregate to monthly by adding up the daily anomalies of each month
tmean_month <- aggregate(list(anom = tmean$anom),
  by = list(month = tmean$month_year),
  FUN = sum, na.rm = T
)

# convert month-year to date (day-month-year) for the x-axis
tmean_month$date <- as.Date(paste0("01-", tmean_month$month), format = "%d-%m-%Y")
tmean_month <- tmean_month[order(tmean_month$date), ]
tmean_month$year <- year(tmean_month$date)

# plot anomalies in every December 1993-2022
plot_c <- ggplot(tmean_month[month(tmean_month$date) == 12, ], aes(x = year, y = anom, fill = year)) +
  geom_bar(stat = "identity", show.legend = FALSE) +
  theme_bw() +
  theme(
    rect = element_rect(fill = "transparent"), panel.border = element_blank(),
    panel.background = element_blank()
  ) +
  scale_fill_continuous(low = "#1170aa", high = "#1170aa") +
  xlab("Time (years)") +
  ylab(expression(paste("Degree days exceeding the 95th percentile  (", degree, "C)")))

plot_c

# prepare plots for the panel
panel_a <- plot_a +
  theme(plot.margin = unit(c(0.5, 0.5, 0, 0.5), "lines")) +
  labs(tag = "A")
panel_b <- plot_b +
  theme(plot.margin = unit(c(0.5, 0.5, 0, 0.5), "lines")) +
  labs(tag = "B")
panel_c <- plot_c +
  theme(plot.margin = unit(c(0.5, 0.5, 0, 0.5), "lines")) +
  labs(tag = "C")

# create panel
panel <- (panel_a) + (panel_b / panel_c) +
  plot_layout(widths = c(2, 1))

# save panel as a png
png(
  file = "output/panel_plot.png",
  width = 300, height = 200, res = 500, units = "mm"
)
panel
dev.off()

#save panel as a pdf
ggsave("output/panel_plot.pdf", panel, width = 12, height = 8)

#save panel as a eps
ggsave("output/panel_plot.eps", panel, width = 12, height = 8)



##### END #####

