#_____________________________________________________________________________
# Script created by Melisa A. Suans, contact at suans.melisa@gmail.com
# R version: 4.4.1
# Version of packages presented in data analysis section of the manuscript
#____________________________________________________________________________

# Set working directory, install and load packages, import dataset from Excel,
# "Ovigenesis_table"

#____________________________________________________________________________

# Data analysis and figures for Experiment 2: egg production dynamics in M. nortoni females

#__________________________________________________________________________
# Load packages ####
library(readxl)
library(bbmle)
library(car)
library(dplyr)
library(effects)
library(emmeans)
library(EnvStats)
library(foreign)
library(ggplot2)
library(ggpubr)
library(gtsummary)
library(lattice)
library(lmtest)
library(lsmeans)
library(MASS)
library(mvtnorm)
library(nnet)
library(outliers)
library(patchwork)
library(performance)
library(pscl)
library(pwr)
library(reshape2)
library(report)
library(rstatix)
library(sjPlot)
library(spaMM)
library(statmod)
library(tidyr)
library(tidyverse)
library(UPG)
library(ggplotify)
library(splines)

# GAM
library(mgcv)
library(gratia)
library(tidygam)
library(dplyr)
library(readr)
library(marginaleffects)

# FIGURES: Number of oocytes for water- and honey-fed females ####
# Ggplot2 theme for figures
theme_set(theme_classic(base_size = 12, base_family = 'sansserif') +
            theme(axis.title.x = element_text(size=12, face="plain", 
                                              colour = "black"), 
                  axis.title.y = element_text(size=12, face="plain", #plan:without format
                                              colour = "black"),    
                  axis.line.x = element_line(color="black", linewidth = 0.3),
                  axis.line.y = element_line(color="black", linewidth = 0.3),
                  plot.title=element_text(size=12, face="bold"),
                  panel.spacing = unit(0.9, 'lines'),
                  legend.margin = margin(0, 0, 0, -15)))

# A. Water-fed females egg dynamic plot ####
My_data <- read_excel("Ovigenesis_table.xlsx", 
                      col_types = c("text", "text", "text", 
                                    "text", "text", "text", "numeric", 
                                    "numeric", "numeric", "numeric", 
                                    "numeric", "numeric", "numeric", 
                                    "numeric", "numeric"))
View(My_data)

# Categorical variables to factors
My_data$Age <- factor(My_data$Age)
My_data$Diet <- factor(My_data$Diet)

levels(My_data$Diet)

# Change the reference       
My_data$Age = relevel(My_data$Age, ref = "0")
My_data$Diet = relevel(My_data$Diet, ref = "Water")

# Egg production, maturation and resorption dynamics plot by diets
# Pivot the data frame into a long format
My_data_long <- My_data %>% pivot_longer(cols=c("Mature", 
                                                "Resorbed", 
                                                "Immature"),
                                         names_to='Oocyte',
                                         values_to='Number_oocyte')
View(My_data_long)

My_data_long$Oocyte <- factor(My_data_long$Oocyte)

# Change the diet name of 0-day-old females from NA to water
My_data_long <- My_data_long %>%
  mutate(Diet = as.character(Diet)) %>%
  mutate(Diet = ifelse(Diet == "NA", "Water", Diet)) %>%
  mutate(Diet = factor(Diet, levels = unique(Diet)))

# Subset for water fed females
My_data_long <- subset(My_data_long, Diet == "Water")
View(My_data_long)

# Calculates mean, sd, se and IC
my_sum <- My_data_long %>%
  group_by(Age, Oocyte) %>%
  summarise( 
    n=n(),
    mean=mean(Number_oocyte),
    sd=sd(Number_oocyte),
    .groups = "drop"
  ) %>%
  mutate(se=sd/sqrt(n))  %>%
  mutate(ic=se * qt((1-0.05)/2 + .5, n-1))

pd = position_dodge(.03)

p1 <- ggplot(my_sum, aes(Age, mean, color=Oocyte, 
                         linetype = Oocyte, group = Oocyte,
                         shape = Oocyte)) +
  geom_line(linewidth = 0.3) + 
  geom_point(size  = 1.8, position = pd)+ ylim(0, 50) +
  scale_color_discrete() +
  scale_x_discrete(limits = c("0", "5", "10", "15", "20", "25")) + #expand = c(0, 0)) +
  geom_errorbar(
    aes(ymin = mean-se, ymax = mean+se, group = Oocyte),
    width = 0.2, position = pd, linewidth = 0.3, linetype = "solid")

p1

number_oocyte_water <- p1 +  ylab("Number of oocytes 
  (mean ± SE)") +xlab("Age (days)") + 
  scale_color_discrete() + 
  scale_fill_discrete()
number_oocyte_water

number_oocyte_water <- number_oocyte_water + theme(text = element_text(family = "sans"))

# B. Honey-fed females egg dynamic plot ####
# Import data
My_data <- read_excel("Ovigenesis_table.xlsx", 
                      col_types = c("text", "text", "text", 
                                    "text", "text", "text", "numeric", 
                                    "numeric", "numeric", "numeric", 
                                    "numeric", "numeric", "numeric", 
                                    "numeric", "numeric"))
View(My_data)

# Categorical variables to factors
My_data$Age <- factor(My_data$Age)
My_data$Diet <- factor(My_data$Diet)

# Change the reference       
My_data$Age = relevel(My_data$Age, ref = "0")

# Egg production, maturation and resorption dynamics plot by diets
# Pivot the data frame into a long format
My_data_long <- My_data %>% pivot_longer(cols=c("Mature", 
                                                "Resorbed", 
                                                "Immature"),
                                         names_to='Oocyte',
                                         values_to='Number_oocyte')
View(My_data_long)

My_data_long$Oocyte <- factor(My_data_long$Oocyte)

# Honey-fed females egg dynamic plot
# Change the diet name of 0-day-old females from NA to water
My_data_long <- My_data_long %>%
  mutate(Diet = as.character(Diet)) %>%
  mutate(Diet = ifelse(Diet == "NA", "Honey", Diet)) %>%
  mutate(Diet = factor(Diet, levels = unique(Diet)))

# Subset for honey fed females
My_data_long <- subset(My_data_long, Diet == "Honey")
View(My_data_long)

# Calculates mean, sd, se and IC
my_sum <- My_data_long %>%
  group_by(Age, Oocyte) %>%
  summarise( 
    n=n(),
    mean=mean(Number_oocyte),
    sd=sd(Number_oocyte),
    .groups = "drop"
  ) %>%
  mutate(se=sd/sqrt(n))  %>%
  mutate(ic=se * qt((1-0.05)/2 + .5, n-1))

my_sum

print(my_sum, n = 30)

pd = position_dodge(.03)

p2 <- ggplot(my_sum, aes(Age, mean, color=Oocyte, 
                         linetype = Oocyte, group = Oocyte,
                         shape = Oocyte)) +
  geom_line(linewidth = 0.3) + 
  geom_point(size  = 1.8, position = pd)+ ylim(0, 50) +
  scale_x_discrete(limits = c("0", "5", "10", "15", "20", "25")) + #expand = c(0, 0)) +
  geom_errorbar(
    aes(ymin = mean-se, ymax = mean+se, group = Oocyte),
    width = 0.2, position = pd, linewidth = 0.3, linetype = "solid")

number_oocyte_honey <- p2 +  ylab("Number of oocytes 
  (mean ± SE)") +xlab("Age (days)") +
  scale_color_discrete() + 
  scale_fill_discrete()
number_oocyte_honey

number_oocyte_honey <- number_oocyte_honey + theme(text = element_text(family = "sans"))

# Combine A-B plots: number of oocytes for water and honey-fed females ####
number_oocyte <- number_oocyte_water + number_oocyte_honey + plot_annotation(
  tag_levels = "A") +
  plot_layout(ncol = 1, 
              heights = c(1, 1),
              axis_titles = "collect",
              guides = "collect")  &
  theme(legend.position = "right",
        legend.justification = c(0.5, 1),
        plot.tag = element_text(size = 11, face="bold"),
        plot.tag.position = c(0.17, 0.97))
number_oocyte

# Save plot
ggsave(
  "plot_number_oocytes_water_honey.pdf",
  plot = last_plot(),
  device = NULL,
  path = NULL,
  scale = 1,
  width = 12,
  height = 14,
  units = "cm",
  dpi = 300,
  limitsize = TRUE,
  bg = NULL,
  create.dir = FALSE
)

# DATA ANALYSIS: egg load, fecundity, egg maturation and resorption rates ####
# for age (5, 10 and 15-days) and diet(water, honey)
My_data <- read_excel("Ovigenesis_table.xlsx", 
                      col_types = c("text", "text", "text", 
                                    "text", "text", "text", "numeric", 
                                    "numeric", "numeric", "numeric", 
                                    "numeric", "numeric", "numeric", 
                                    "numeric", "numeric"))
View(My_data)

# Exclude 0, 20 and 25-day-old cohorts
My_data <- subset(My_data, !(Age %in% c(0, 20, 25)))
View(My_data)

# Categorical variables to factors
My_data$Age <- factor(My_data$Age)
My_data$Diet <- factor(My_data$Diet)

# Change the reference       
My_data$Age = relevel(My_data$Age, ref = "5")
My_data$Diet = relevel(My_data$Diet, ref = "Water")

# Categorical variables to factors
levels(My_data$Diet)
levels(My_data$Age)

My_data$Age <- factor(My_data$Age, levels = c("5", "10", "15"))
My_data$Diet <- factor(My_data$Diet, levels = c("Water", "Honey"))

# C. Egg load ####
gam.poiss <- gam(Mature ~ Diet + Age + 
                   s(Hind_tibia_length, bs="cr", k = 3),
                 data = My_data, family = poisson(link = "log"),
                 method = "REML")
summary(gam.poiss)
anova(gam.poiss)

# Dispersion parameter
dispersion <- sum(residuals(gam.poiss, type = "deviance")^2) / gam.poiss$df.residual
dispersion 

# Tweedie models for underdispersed data
gam.tw <- gam(Mature ~ Diet + Age + 
                s(Hind_tibia_length, bs="cr", k = 3),
              data = My_data, family = tw(link = "log"),
              method = "REML")
summary(gam.tw)
anova(gam.tw)

gam.tw1 <- gam(Mature ~ Age + 
                 s(Hind_tibia_length, bs="cr", k = 3),
               data = My_data, family = tw(link = "log"),
               method = "REML")
summary(gam.tw1)
anova(gam.tw1)

gam.tw2 <- gam(Mature ~ Diet*Age + 
                 s(Hind_tibia_length, bs="cr", k = 3),
               data = My_data, family = poisson(link = "log"),
               method = "REML")
summary(gam.tw2)
anova(gam.tw2)

gam.tw3 <- gam(Mature ~ Diet + Age + 
                 s(Hind_tibia_length, bs="cr", by = Diet, k =3),
               data = My_data, family = poisson(link = "log"),
               method = "REML")
summary(gam.tw3)
anova(gam.tw3)

gam.tw4 <- gam(Mature ~ Diet + Age + 
                 s(Hind_tibia_length, bs="cr", by = Age, k =3),
               data = My_data, family = poisson(link = "log"),
               method = "REML")
summary(gam.tw4)
anova(gam.tw4)

# AIC
AIC(gam.poiss, gam.tw, gam.tw1, gam.tw2, gam.tw3, gam.tw4)

# Fitted model (lowest AIC)
gam.tw <- gam(Mature ~ Diet + Age + 
                s(Hind_tibia_length, bs="cr", k = 3),
              data = My_data, family = tw(link = "log"),
              method = "REML")
summary(gam.tw)
anova(gam.tw)

# Model checking
# QQplots have to be normal and residuals vs fitted must show no patterns
gam.check(gam.tw, rep=500) # You need a big data set, so 500
appraise(gam.tw, method = "simulate")

# Compare between Age treatments for each Diet and between Diets for each age
# Post-hoc analysis
emmeans(gam.tw, pairwise ~ Diet + Age, type = "response", infer = T)

# Table of GAM output for fitted model and IRRs
gam(Mature ~ Diet + Age + 
      s(Hind_tibia_length, bs="cr", k = 3),
    data = My_data, family = tw(link = "log"),
    method = "REML") %>% 
  tbl_regression(exponentiate = TRUE) 

# Get publication ready table and IRRs
tbl_regression(gam.tw, exponentiate=T, add_pairwise_contrasts = T) %>%
  add_significance_stars(hide_p = F, hide_se = T, hide_ci = F) %>%
  bold_p()

# Plot smooth effects (partial effects)
p <- draw(gam.tw, scales = "fixed")

p & labs(y = "Partial effect",
         x = "Hind tibia length (mm)") 

# Partial effects
draw(gam.tw, select = "s(Hind_tibia_length)", 
     residuals = FALSE, 
     fun = exp) +
  labs(x = "Hind tibia length (mm)", 
       y = "Egg load") +
  theme_minimal() +
  theme(legend.position = "top")

# Predict
lvl_age <- levels(My_data$Age)[1]

newdat <- expand.grid(
  Hind_tibia_length = seq(min(My_data$Hind_tibia_length, na.rm = TRUE),
                          max(My_data$Hind_tibia_length, na.rm = TRUE),
                          length.out = 200),
  Diet = levels(My_data$Diet),
  Age = lvl_age
)

# Predict
red <- mgcv::predict.gam(gam.tw, newdata = newdat, type = "response", se.fit = TRUE)

# Save predictions
newdat$fit <- red$fit
newdat$se  <- red$se.fit

smooth_plot <- ggplot(newdat, 
                               aes(x = Hind_tibia_length, y = fit, color = Diet, fill = Diet)) +
  geom_line(aes(linetype=Diet), size = 0.8) +
  geom_ribbon(aes(ymin = fit - 1.96 * se, ymax = fit + 1.96 * se),
              alpha = 0.2, color = NA) +
  labs(x = "Hind tibia length (mm)",
       y = "Egg load",
       color = "Diet", fill = "Diet", linetype = "Diet")

smooth_plot_egg_load <- smooth_plot +
  scale_fill_discrete(limits = c("Honey", "Water"), labels = c("Honey", "Water")) +
  scale_color_discrete(limits = c("Honey", "Water"), labels = c("Honey", "Water")) +
  scale_linetype_discrete(limits = c("Honey", "Water"), labels = c("Honey", "Water")) +
  theme_classic(base_size = 12, base_family = "sans") +  # <- clave para PDF seguro
  theme(axis.title.x = element_text(size=12, face="plain", colour="black"),
        axis.title.y = element_text(size=12, face="plain", colour="black"),
        axis.line.x = element_line(color="black", linewidth=0.3),
        axis.line.y = element_line(color="black", linewidth=0.3),
        plot.title = element_text(size=12, face="bold"),
        panel.spacing = unit(0.9, 'lines'),
        legend.margin = margin(0, 0, 0, -15),
        legend.position = "top")
smooth_plot_egg_load


# # Save plot
# ggsave("smooth_plot_egg_load.pdf",
#   plot = last_plot(),
#   device = NULL,
#   path = NULL,
#   scale = 1,
#   width = 9,
#   height = 8,
#   units = "cm",
#   dpi = 300,
#   limitsize = TRUE,
#   bg = NULL,
#   create.dir = FALSE
# )

# Plot predictions of the linear fixed effects
plot_egg_load <- plot_model(gam.tw, 
                            type="pred", 
                            terms = c("Age", "Diet"),
                            title = "") +
  ylab("Egg load") +
  xlab("Age (days)") +
  theme_classic(base_size = 12, base_family = "sans") +
  theme(axis.title.x = element_text(size=12, face="plain", colour="black"),
        axis.title.y = element_text(size=12, face="plain", colour="black"),
        axis.line.x = element_line(color="black", linewidth=0.3),
        axis.line.y = element_line(color="black", linewidth=0.3),
        plot.title = element_text(size=12, face="bold"),
        panel.spacing = unit(0.9, 'lines'),
        legend.margin = margin(0, 0, 0, -15),
        legend.position = "top")

plot_egg_load <- plot_egg_load +
  aes(linetype=group_col) + 
  scale_fill_discrete(
    limits = c("Honey", "Water"),
    labels = c("Honey", "Water")) +
  scale_color_discrete(
    limits = c("Honey", "Water"),
    labels = c("Honey", "Water")) +
  scale_linetype_discrete(
    limits = c("Honey", "Water"),
    labels = c("Honey", "Water"), name = "Diet") +
  annotate("text",
           x = 5,
           y = 23.8,
           label = "ab",
           size = 4) +
  annotate("text",
           x = 10,
           y = 24.8,
           label = "a",
           size = 4) +
  annotate("text",
           x = 15,
           y = 21,
           label = "b",
           size = 4)
plot_egg_load

ggsave(
  "plot_egg_load.pdf",
  plot = last_plot(),
  device = NULL,
  path = NULL,
  scale = 1,
  width = 9,
  height = 8,
  units = "cm",
  dpi = 300,
  limitsize = TRUE,
  bg = NULL,
  create.dir = FALSE
)

# D. Fecundity ####
gam.poiss <- gam(FEC ~ Diet*Age + 
                   s(Hind_tibia_length, bs = "cr", k = 3),
                 data = My_data, family = poisson(link = "log"),
                 method = "REML")
summary(gam.poiss)
anova(gam.poiss)

# Dispersion parameter
dispersion <- sum(residuals(gam.poiss, type = "deviance")^2) / gam.poiss$df.residual
dispersion

gam.poiss2 <- gam(FEC ~ Diet + Age + 
                 s(Hind_tibia_length, bs = "cr", k = 3),
               data = My_data, family = poisson(link = "log"),
               method = "REML")
summary(gam.poiss2)
anova(gam.poiss2)

gam.poiss3 <- gam(FEC ~ Diet + Age + 
                    s(Hind_tibia_length, by=Diet, bs = "cr", k = 3) +
                    s(Hind_tibia_length, by=Age, bs = "cr", k = 3),
                  data = My_data, family = poisson(link = "log"),
                  method = "REML")
summary(gam.poiss3)
anova(gam.poiss3)

gam.poiss4 <- gam(FEC ~ Diet + Age + 
                    s(Hind_tibia_length, by=Diet, bs = "cr", k = 3),
                  data = My_data, family = poisson(link = "log"),
                  method = "REML")
summary(gam.poiss4)
anova(gam.poiss4)

# AIC
AIC(gam.poiss, gam.poiss2, gam.poiss3, gam.poiss4)

# Fitted model (lowest AIC)
gam.poiss2 <- gam(FEC ~ Diet + Age + 
                 s(Hind_tibia_length, bs = "cr", k = 3),
               data = My_data, family = poisson(link = "log"),
               method = "REML")
summary(gam.poiss2)
anova(gam.poiss2)

# Model checking
# QQplots have to be normal and residuals vs fitted must show no patterns
gam.check(gam.poiss2, rep=500) # You need a big data set, so 500
appraise(gam.poiss2, method = "simulate")

# Compare between Age treatments for each Diet and between Diets for each age
# Post-hoc analysis
emmeans(gam.poiss2, pairwise ~ Diet + Age, type = "response", infer = T)

# Table of GAM output for final model and IRRs
gam(FEC ~ Diet + Age + 
      s(Hind_tibia_length),
    data = My_data, family = poisson(link = "log"),
    method = "REML") %>% 
  tbl_regression(exponentiate = TRUE) 

# Get publication ready table and IRRs
tbl_regression(gam.poiss2, exponentiate=T, add_pairwise_contrasts = T) %>%
  add_significance_stars(hide_p = F, hide_se = T, hide_ci = F) %>%
  bold_p()

# Plot smooth effects (partial effects)
p <- draw(gam.poiss2, scales = "fixed")

p & labs(y = "Partial effect",
         x = "Hind tibia length (mm)") 

# Predict
lvl_age <- levels(My_data$Age)[1]

newdat <- expand.grid(
  Hind_tibia_length = seq(min(My_data$Hind_tibia_length, na.rm = TRUE),
                          max(My_data$Hind_tibia_length, na.rm = TRUE),
                          length.out = 200),
  Diet = levels(My_data$Diet),
  Age = lvl_age
)

# Predict
red <- mgcv::predict.gam(gam.poiss2, newdata = newdat, type = "response", se.fit = TRUE)

# Save predictions
newdat$fit <- red$fit
newdat$se  <- red$se.fit

smooth_plot <- ggplot(newdat, 
                      aes(x = Hind_tibia_length, y = fit, color = Diet, fill = Diet)) +
  geom_line(aes(linetype=Diet), size = 0.8) +
  geom_ribbon(aes(ymin = fit - 1.96 * se, ymax = fit + 1.96 * se),
              alpha = 0.2, color = NA) +
  labs(x = "Hind tibia length (mm)",
       y = "Fecundity",
       color = "Diet", fill = "Diet", linetype = "Diet")

smooth_plot_fecundity <- smooth_plot +
  scale_fill_discrete(limits = c("Honey", "Water"), labels = c("Honey", "Water")) +
  scale_color_discrete(limits = c("Honey", "Water"), labels = c("Honey", "Water")) +
  scale_linetype_discrete(limits = c("Honey", "Water"), labels = c("Honey", "Water")) +
  theme_classic(base_size = 12, base_family = "sans") +  # <- clave para PDF seguro
  theme(axis.title.x = element_text(size=12, face="plain", colour="black"),
        axis.title.y = element_text(size=12, face="plain", colour="black"),
        axis.line.x = element_line(color="black", linewidth=0.3),
        axis.line.y = element_line(color="black", linewidth=0.3),
        plot.title = element_text(size=12, face="bold"),
        panel.spacing = unit(0.9, 'lines'),
        legend.margin = margin(0, 0, 0, -15),
        legend.position = "top")
smooth_plot_fecundity


# Save plot
ggsave(
  "smooth_plot_fecundity.tiff",
  plot = last_plot(),
  device = NULL,
  path = NULL,
  scale = 1,
  width = 9,
  height = 8,
  units = "cm",
  dpi = 300,
  limitsize = TRUE,
  bg = NULL,
  create.dir = FALSE
)

# Plot predictions of the linear fixed effects
plot_fecundity <- plot_model(gam.poiss2, 
                             type="pred", 
                             terms = c("Age", "Diet"),
                             title = "") +
  ylab("Fecundity") +
  xlab("Age (days)") +
  theme_classic(base_size = 12, base_family = "sans") +
  theme(axis.title.x = element_text(size=12, face="plain", colour="black"),
        axis.title.y = element_text(size=12, face="plain", colour="black"),
        axis.line.x = element_line(color="black", linewidth=0.3),
        axis.line.y = element_line(color="black", linewidth=0.3),
        plot.title = element_text(size=12, face="bold"),
        panel.spacing = unit(0.9, 'lines'),
        legend.margin = margin(0, 0, 0, -15),
        legend.position = "top")

plot_fecundity <- plot_fecundity +
  aes(linetype=group_col) + 
  scale_fill_discrete(
    limits = c("Honey", "Water"),
    labels = c("Honey", "Water")) +
  scale_color_discrete(
    limits = c("Honey", "Water"),
    labels = c("Honey", "Water")) +
  scale_linetype_discrete(
    limits = c("Honey", "Water"),
    labels = c("Honey", "Water"), name = "Diet") +
  annotate("text",
           x = 5,
           y = 75.6,
           label = "a*",
           size = 4) +
  annotate("text",
           x = 10,
           y = 69.93,
           label = "a*",
           size = 4) +
  annotate("text",
           x = 15,
           y = 54.93,
           label = "b*",
           size = 4)
plot_fecundity

ggsave(
  "plot_fecundity.tiff",
  plot = last_plot(),
  device = NULL,
  path = NULL,
  scale = 1,
  width = 9,
  height = 8,
  units = "cm",
  dpi = 300,
  limitsize = TRUE,
  bg = NULL,
  create.dir = FALSE
)

# Combine C-D plots ####
egg_load_fecundity <- plot_egg_load + smooth_plot_egg_load +
  plot_fecundity + smooth_plot_fecundity +
  plot_annotation(tag_levels = "A") +
  plot_layout(guides = "collect",
              widths = c(1.5, 1)) & 
  theme(legend.position = "none",
        legend.justification = c(0.5, 1),
        plot.tag = element_text(size = 11, face="bold"))
egg_load_fecundity

# Save
ggsave(
  "plot_egg_load_fecundity.pdf",
  plot = last_plot(),
  device = NULL,
  path = NULL,
  scale = 1,
  width = 17,
  height = 14,
  units = "cm",
  dpi = 300,
  limitsize = TRUE,
  bg = NULL,
  create.dir = FALSE
)

# D. Egg maturation rates ####
# Create the response variable
Response <- cbind(My_data$Mature, My_data$Immature)

m1 <- gam(Response ~ Diet*Age + 
            s(Hind_tibia_length), data= My_data, 
          family = binomial(logit))
summary(m1)
anova(m1)

m2 <- gam(Response ~ Diet + Age + 
            s(Hind_tibia_length), data= My_data, 
          family = binomial(logit))
summary(m2)
anova(m2)

m3 <- gam(Response ~ Diet + Age + 
            s(Hind_tibia_length, by = Diet) +
            s(Hind_tibia_length, by = Age), data= My_data, 
          family = binomial(logit))
summary(m3)
anova(m3)

m4 <- gam(Response ~ Diet + Age + 
            s(Hind_tibia_length, by = Diet), data= My_data, 
          family = binomial(logit))
summary(m4)
anova(m4)

m5 <- gam(Response ~ Age + 
            s(Hind_tibia_length), data= My_data, 
          family = binomial(logit))
summary(m5)
anova(m5)

dispersion <- sum(residuals(m1, type = "deviance")^2) / m1$df.residual
dispersion <- sum(residuals(m4, type = "deviance")^2) / m4$df.residual
dispersion

AIC(m1, m2, m3, m4, m5)

# Fitted model (lowest AIC)
m4 <- gam(Response ~ Diet + Age + 
            s(Hind_tibia_length, by = Diet), data= My_data, 
          family = binomial(logit))
summary(m4)
anova(m4)

# Model checking
# QQplots have to be normal and residuals vs fitted must show no patterns
gam.check(m4, rep=500) # You need a big data set, so 500
appraise(m4, method = "simulate")

# Check for possible outliers
# Cook's Distance
cooks_dist <- cooks.distance(m4)

plot(cooks_dist, type = "h", main = "Cook's Distance", ylab = "Distance", xlab = "Observation")
abline(h = 4 / nrow(My_data), col = "red", lty = 2)

# Deviance residuals
deviance_resid <- residuals(m4, type = "deviance")

plot(deviance_resid, pch = 19, main = "Residuos Deviance", ylab = "Residuals", xlab = "Observation")
abline(h = c(-2, 2), col = "red", lty = 2)

# Which are outliers?
outlier_indices <- which(abs(deviance_resid) > 2)
outlier_indices

# Eliminate the outliers and run the model again
My_data <- My_data[-c(33),]

# Check that the outlier's elimination do not improve the fit of the model
# The data become more underdispersed and Q-Q plots are not so good.

# I decided to maintain this outlier

# Compare between Age treatments for each Diet and between Diets for each age
# Post-hoc analysis
emmeans(m4, pairwise ~ Diet + Age, type = "response", infer = T)

# Table of GAM output for final model and ORs
gam(Response ~ Diet + Age + 
      s(Hind_tibia_length, by = Diet), data= My_data, 
    family = binomial(logit)) %>% 
  tbl_regression(exponentiate = TRUE) 

# Get publication ready table and ORs
tbl_regression(m4, exponentiate=T, add_pairwise_contrasts = T) %>%
  add_significance_stars(hide_p = F, hide_se = T, hide_ci = F) %>%
  bold_p()

# Plot smooth effects (partial effects)
p <- draw(m4, scales = "fixed")

p & labs(y = "Partial effect",
         x = "Hind tibia length (mm)") 

# Plot predictions of the linear fixed effects
plot_maturation <- plot_model(m4, 
                             type="pred", 
                             terms = c("Age", "Diet"),
                             title = "",
                             ci.lvl = 0.95) +
  ylab("Egg maturation") +
  xlab("Age (days)") +
  theme_classic(base_size = 12, base_family = "sans") +
  theme(axis.title.x = element_text(size=12, face="plain", colour="black"),
        axis.title.y = element_text(size=12, face="plain", colour="black"),
        axis.line.x = element_line(color="black", linewidth=0.3),
        axis.line.y = element_line(color="black", linewidth=0.3),
        plot.title = element_text(size=12, face="bold"),
        panel.spacing = unit(0.9, 'lines'),
        legend.margin = margin(0, 0, 0, -15),
        legend.position = "top")

plot_maturation <- plot_maturation +
  aes(linetype=group_col) + 
  scale_fill_discrete(
    limits = c("Honey", "Water"),
    labels = c("Honey", "Water")) +
  scale_color_discrete(
    limits = c("Honey", "Water"),
    labels = c("Honey", "Water")) +
  scale_linetype_discrete(
    limits = c("Honey", "Water"),
    labels = c("Honey", "Water"), name = "Diet") +
  annotate("text",
           x = 5,
           y = 0.385,
           label = "a",
           size = 4) +
  annotate("text",
           x = 10,
           y = 0.425,
           label = "ab",
           size = 4) +
  annotate("text",
           x = 15,
           y = 0.464,
           label = "b",
           size = 4)
plot_maturation 

ggsave(
  "plot_maturation.pdf",
  plot = last_plot(),
  device = NULL,
  path = NULL,
  scale = 1,
  width = 9,
  height = 8,
  units = "cm",
  dpi = 300,
  limitsize = TRUE,
  bg = NULL,
  create.dir = FALSE
)

# E. Egg resorption rates ####
My_data <- read_excel("Ovigenesis_table.xlsx", 
                      col_types = c("text", "text", "text", 
                                    "text", "text", "text", "numeric", 
                                    "numeric", "numeric", "numeric", 
                                    "numeric", "numeric", "numeric", 
                                    "numeric", "numeric"))
View(My_data)

# Exclude 0, 5, 20 and 25-day-old cohorts
My_data <- subset(My_data, !(Age %in% c(0, 5, 20, 25)))
View(My_data)

# Categorical variables to factors
My_data$Age <- factor(My_data$Age)
My_data$Diet <- factor(My_data$Diet)

# Change the reference       
My_data$Age = relevel(My_data$Age, ref = "10")
My_data$Diet = relevel(My_data$Diet, ref = "Water")

# Categorical variables to factors
levels(My_data$Diet)
levels(My_data$Age)

My_data$Age <- factor(My_data$Age, levels = c("10", "15"))
My_data$Diet <- factor(My_data$Diet, levels = c("Water", "Honey"))

# Model GLM binomial
Response <- cbind(My_data$Resorbed, My_data$Mature)

r1 <- gam(Response ~ Diet*Age + s(Hind_tibia_length), 
          data= My_data, 
          family = binomial(logit))
summary(r1)
anova(r1)

r2 <- gam(Response ~ Diet + Age + s(Hind_tibia_length), 
          data= My_data, 
          family = binomial(logit))
summary(r2)
anova(r2)

r3 <- gam(Response ~ Diet + Age + 
            s(Hind_tibia_length, by = Diet) +
            s(Hind_tibia_length, by = Age), 
          data= My_data, 
          family = binomial(logit))
summary(r3)
anova(r3)

r4 <- gam(Response ~ Diet + Age + 
            s(Hind_tibia_length, by = Diet), 
          data= My_data, 
          family = binomial(logit))
summary(r4)
anova(r4)

AIC(r1, r2, r3, r4)

# Fitted model (lowest AIC)
r2 <- gam(Response ~ Diet + Age + s(Hind_tibia_length), 
          data= My_data, 
          family = binomial(logit))
summary(r2)
anova(r2)

dispersion <- sum(residuals(r2, type = "deviance")^2) / r2$df.residual
dispersion

# Quasibinomial model
r2_q <- gam(Response ~ Diet + Age + s(Hind_tibia_length), 
          data= My_data, 
          family = quasibinomial(logit))
summary(r2_q)
anova(r2_q)

# Check for possible outliers
# Deviance residuals
deviance_resid <- residuals(r2_q_without_outlier2, type = "deviance")

plot(deviance_resid, pch = 19, main = "Residuos Deviance", ylab = "Residuals", xlab = "Observation")
abline(h = c(-2, 2), col = "red", lty = 2)

# Which are possible outliers?
outlier_indices <- which(abs(deviance_resid) > 3)
outlier_indices

# Eliminate the most influential value and run the model again
My_data <- My_data[-c(28),]

# We decided to eliminate this influential value because it corresponds to a
# 10-day-old female which had no resorbed oocytes at this age, uncommon for this age cohort
# (according to results)

# Compare between Age treatments for each Diet and between Diets for each age
# Post-hoc analysis
emmeans(r2_q, pairwise ~ Diet + Age, type = "response", infer = T)

# Table of GAM output for final model and ORs
gam(Response ~ Diet + Age + s(Hind_tibia_length), 
          data= My_data, 
          family = quasibinomial(logit)) %>% 
  tbl_regression(exponentiate = TRUE) 

# Get publication ready table and ORs
tbl_regression(r2_q, exponentiate=T, add_pairwise_contrasts = T) %>%
  add_significance_stars(hide_p = F, hide_se = T, hide_ci = F) %>%
  bold_p()

# Plot smooth effects (partial effects)
p <- draw(r2_q, scales = "fixed")

p & labs(y = "Partial effect",
         x = "Hind tibia length (mm)") 

# Plot predictions of the linear fixed effects
plot_resorption <- plot_model(r2_q, 
                              type="pred", 
                              terms = c("Age", "Diet"),
                              title = "") +
  ylab("Egg resorption") +
  xlab("Age (days)") +
  theme_classic(base_size = 12, base_family = "sans") +
  theme(axis.title.x = element_text(size=12, face="plain", colour="black"),
        axis.title.y = element_text(size=12, face="plain", colour="black"),
        axis.line.x = element_line(color="black", linewidth=0.3),
        axis.line.y = element_line(color="black", linewidth=0.3),
        plot.title = element_text(size=12, face="bold"),
        panel.spacing = unit(0.9, 'lines'),
        legend.margin = margin(0, 0, 0, -15),
        legend.position = "top")

plot_resorption <- plot_resorption +
  aes(linetype=group_col) + 
  scale_fill_discrete(
    limits = c("Honey", "Water"),
    labels = c("Honey", "Water")) +
  scale_color_discrete(
    limits = c("Honey", "Water"),
    labels = c("Honey", "Water")) +
  scale_linetype_discrete(
    limits = c("Honey", "Water"),
    labels = c("Honey", "Water"), name = "Diet")
  
plot_resorption

# Final plot: add a point in 5 day old cohort
pred_data <- plot_model(r2_q, type = "pred", 
                        terms = c("Age", "Diet"), title = "")$data

pred_data <- as.data.frame(pred_data)

pred_data <- pred_data %>%
  mutate(x_num = case_when(
    x == "5" ~ 5,
    x == "10" ~ 10,
    x == "15" ~ 15,
    TRUE ~ NA_real_
  ))

pred_data <- pred_data %>% select(-x)

pred_data$group <- factor(pred_data$group, levels = c("Honey", "Water"))

# Create Age=5, pred=0
puntos_extra <- data.frame(
  x_num = 5,
  group = factor(c("Honey", "Water"), levels = c("Honey", "Water")),
  predicted = 0,
  conf.low = NA,
  conf.high = NA
)

# Unify
datos_plot <- bind_rows(pred_data, puntos_extra)

# Plot
plot_resorption <- ggplot(datos_plot, aes(x = x_num, y = predicted, group = group)) +
  geom_point(aes(color = ifelse(x_num == 5, "5", as.character(group))), size = 2.48) +
  geom_linerange(
    aes(ymin = conf.low, ymax = conf.high, color = group, linetype = group),
    size = 0.7,
    show.legend = FALSE,
    key_glyph = "path" ) +
  
  geom_line(aes(color = group, linetype = group), linetype = 0) +
  
  scale_color_manual(
    name = "Diet",
    values = c("Honey" = "#F8766D", "Water" = "#00BFC4", "5" = "azure4"),
    labels = c("Honey", "Water"),
    breaks = c("Honey", "Water") 
  ) +

  scale_linetype_manual(
    name = "Diet",
    values = c("Honey" = "solid", "Water" = "22"),
    labels = c("Honey", "Water")
  ) +
  
  ylab("Egg resorption") +
  xlab("Age (days)") +
  scale_x_continuous(breaks = c(5, 10, 15), labels = c("5", "10", "15")) +
  scale_y_continuous(labels = scales::label_percent(accuracy = 1)) +
  theme(
    legend.position = "top",
    aspect.ratio = 0.68,
    legend.margin = margin(t = 17.5, b = 5),
    plot.margin = margin(t = 5, r = -10, b = 5, l = -10)
  ) +

  guides(
    color = guide_legend(
      override.aes = list(
        linetype = c("solid", "22"),
        shape = c(16, 16),              
        color = c("#F8766D", "#00BFC4") 
      )
    )
  )

plot_resorption <- plot_resorption +
  theme_classic(base_size = 12, base_family = "sans") +
  theme(axis.title.x = element_text(size=12, face="plain", colour="black"),
        axis.title.y = element_text(size=12, face="plain", colour="black"),
        axis.line.x = element_line(color="black", linewidth=0.3),
        axis.line.y = element_line(color="black", linewidth=0.3),
        plot.title = element_text(size=12, face="bold"),
        panel.spacing = unit(0.9, 'lines'),
        legend.margin = margin(0, 0, 0, -15),
        legend.position = "top") +
  annotate("text",
           x = 10,
           y = 0.32,
           label = "a*",
           size = 4) +
  annotate("text",
           x = 15,
           y = 0.50,
           label = "b*",
           size = 4)
plot_resorption

ggsave(
  "plot_resorption.pdf",
  plot = last_plot(),
  device = NULL,
  path = NULL,
  scale = 1,
  width = 9,
  height = 8,
  units = "cm",
  dpi = 300,
  limitsize = TRUE,
  bg = NULL,
  create.dir = FALSE
)

# DATA ANALYSIS only for honey-fed females ####
My_data <- read_excel("Ovigenesis_table.xlsx", 
                      col_types = c("text", "text", "text", 
                                    "text", "text", "text", "numeric", 
                                    "numeric", "numeric", "numeric", 
                                    "numeric", "numeric", "numeric", 
                                    "numeric", "numeric"))
View(My_data)

# Categorical variables to factors
My_data$Age <- factor(My_data$Age)
My_data$Diet <- factor(My_data$Diet)

# Exclude 0-day-old cohort
My_data <- subset(My_data, !(Age %in% c(0)))

# Subset for honey fed females
My_data <- subset(My_data, Diet == "Honey")
View(My_data)

# Change the reference       
My_data$Age = relevel(My_data$Age, ref = "5")
My_data$Diet = relevel(My_data$Diet, ref = "Water")

# F. Egg load ####
# Poisson GAM
gam.poiss <- gam(Mature ~ Age + 
                   s(Hind_tibia_length, k = 5),
                 data = My_data, family = poisson(link = "log"),
                 method = "REML")
summary(gam.poiss)
anova(gam.poiss)

dispersion <- sum(residuals(gam.poiss, type = "deviance")^2) / gam.poiss$df.residual
dispersion

# A Poisson-Tweedie distribution is applied to deal with underdispersion data (mean > variance)
gam.tw1 <- gam(Mature ~ Age + 
                 s(Hind_tibia_length, bs = "cr", k = 3),
               data = My_data, family = tw(link = "log"),
               method = "REML")
summary(gam.tw1)
anova(gam.tw1)

AIC(gam.poiss, gam.tw1)

# Fitted model (lowest AIC)
gam.tw1 <- gam(Mature ~ Age + 
                 s(Hind_tibia_length, bs = "cr", k = 3),
               data = My_data, family = tw(link = "log"),
               method = "REML")
summary(gam.tw1)
anova(gam.tw1)

# Model checking
# QQplots have to be normal and residuals vs fitted must show no patterns
gam.check(gam.tw1, rep=500) # You need a big data set, so 500
appraise(gam.tw1, method = "simulate")

# Compare between Age treatments for each Diet and between Diets for each age
# Post-hoc analysis
emmeans(gam.tw1, pairwise ~ Age, type = "response", infer = T)

# Table of GAM output for fitted model and IRRs
gam(Mature ~ Age + 
      s(Hind_tibia_length, bs = "cr", k = 3),
    data = My_data, family = tw(link = "log"),
    method = "REML") %>% 
  tbl_regression(exponentiate = TRUE) 

# Get publication ready table and IRRs
tbl_regression(gam.tw1, exponentiate=T, add_pairwise_contrasts = T) %>%
  add_significance_stars(hide_p = F, hide_se = T, hide_ci = F) %>%
  bold_p()

# plot predictions (SJplot)
plot_egg_load_honey <- plot_model(gam.tw1, 
                                  type="pred", 
                                  terms = c("Age"),
                                  title = "",
                                  colors = '#F8766D') +
  ylab("Egg load") +
  xlab("Age (days)") +
  theme_classic(base_size = 12, base_family = "sans") +
  theme(axis.title.x = element_text(size=12, face="plain", colour="black"),
        axis.title.y = element_text(size=12, face="plain", colour="black"),
        axis.line.x = element_line(color="black", linewidth=0.3),
        axis.line.y = element_line(color="black", linewidth=0.3),
        plot.title = element_text(size=12, face="bold"),
        panel.spacing = unit(0.9, 'lines'),
        legend.margin = margin(0, 0, 0, -15),
        legend.position = "top")

plot_egg_load_honey

# Save plot
ggsave(
  "plot_egg_load_honey.pdf",
  plot = last_plot(),
  device = NULL,
  path = NULL,
  scale = 1,
  width = 9,
  height = 8,
  units = "cm",
  dpi = 300,
  limitsize = TRUE,
  bg = NULL,
  create.dir = FALSE
)

# G. Fecundity ####
gam.poiss <- gam(FEC ~ Age + 
                   s(Hind_tibia_length, bs = "cr", k = 3),
                 data = My_data, family = poisson(link = "log"),
                 method = "REML")
summary(gam.poiss)
anova(gam.poiss)

dispersion <- sum(residuals(gam.poiss, type = "deviance")^2) / gam.poiss$df.residual
dispersion

# Model checking
# QQplots have to be normal and residuals vs fitted must show no patterns
gam.check(gam.poiss, rep=500) # You need a big data set, so 500
appraise(gam.poiss, method = "simulate")

# Compare between Age treatments for each Diet and between Diets for each age
# Post-hoc analysis
emmeans(gam.poiss, pairwise ~ Age, type = "response", infer = T)

# Table of GAM output for fitted model and IRRs
gam(FEC ~ Age + 
      s(Hind_tibia_length),
    data = My_data, family = poisson(link = "log"),
    method = "REML") %>% 
  tbl_regression(exponentiate = TRUE) 

# Get publication ready table and IRRs
tbl_regression(gam.poiss, exponentiate=T, add_pairwise_contrasts = T) %>%
  add_significance_stars(hide_p = F, hide_se = T, hide_ci = F) %>%
  bold_p()

# Plot smooth effects (partial effects)
p <- draw(gam.poiss, scales = "fixed")

p & labs(y = "Partial effect",
         x = "Hind tibia length (mm)") 

# Plot predictions of linear fixed effects
plot_fecundity_honey <- plot_model(gam.poiss, 
                                   type="pred", 
                                   terms = c("Age"),
                                   title = "",
                                   colors = '#F8766D') +
  ylab("Fecundity") +
  xlab("Age (days)") +
  theme_classic(base_size = 12, base_family = "sans") +
  theme(axis.title.x = element_text(size=12, face="plain", colour="black"),
        axis.title.y = element_text(size=12, face="plain", colour="black"),
        axis.line.x = element_line(color="black", linewidth=0.3),
        axis.line.y = element_line(color="black", linewidth=0.3),
        plot.title = element_text(size=12, face="bold"),
        panel.spacing = unit(0.9, 'lines'),
        legend.margin = margin(0, 0, 0, -15),
        legend.position = "top")
plot_fecundity_honey

ggsave(
  "plot_fecundity_honey.pdf",
  plot = last_plot(),
  device = NULL,
  path = NULL,
  scale = 1,
  width = 9,
  height = 8,
  units = "cm",
  dpi = 300,
  limitsize = TRUE,
  bg = NULL,
  create.dir = FALSE
)

# H. Egg maturation rates ####
# Create the response variable
Response <- cbind(My_data$Mature, My_data$Immature)

m1 <- gam(Response ~ Age + 
            s(Hind_tibia_length, bs = "cr", k = 3), data= My_data, 
          family = binomial(logit))
summary(m1)
anova(m1)

m2 <- gam(Response ~ Age + 
            s(Hind_tibia_length, bs = "cr", by = Age, k = 3), data= My_data, 
          family = binomial(logit))
summary(m2)
anova(m2)

m3 <- gam(Response ~ s(Hind_tibia_length, bs = "cr", k = 3), data= My_data, 
          family = binomial(logit))
summary(m3)
anova(m3)

m4 <- gam(Response ~ 1, data= My_data, 
          family = binomial(logit))
summary(m4)
anova(m4)

AIC(m1, m2, m3, m4)

dispersion <- sum(residuals(m1, type = "deviance")^2) / m1$df.residual
dispersion

# Fitted model (lowest AIC)
m1 <- gam(Response ~ Age + 
            s(Hind_tibia_length, bs = "cr", k = 3), data= My_data, 
          family = binomial(logit))
summary(m1)
anova(m1)

# Model checking
# QQplots have to be normal and residuals vs fitted must show no patterns
gam.check(m1, rep=500) # You need a big data set, so 500
appraise(m1, method = "simulate")

# Check for possible outliers
# Deviance residuals
deviance_resid <- residuals(m1, type = "deviance")

plot(deviance_resid, pch = 19, main = "Residuos Deviance", ylab = "Residuals", xlab = "Observation")
abline(h = c(-2, 2), col = "red", lty = 2)

# Which are outliers?
outlier_indices <- which(abs(deviance_resid) > 2)
outlier_indices

# Eliminate the outliers and run the model again
My_data <- My_data[-c(5),] 

# It is not better to eliminate the outlier, according to Q-Q plots and dispersion parameter

# Compare between Age treatments for each Diet and between Diets for each age
# Post-hoc analysis
emmeans(m1, pairwise ~ Age, type = "response", infer = T)

# Table of GAM output for fitted model and IRRs
gam(Response ~ Age + 
      s(Hind_tibia_length, bs = "cr", k = 3), data= My_data, 
    family = binomial(logit)) %>% 
  tbl_regression(exponentiate = TRUE) 

# Get publication ready table and ORs
tbl_regression(m1, exponentiate=T, add_pairwise_contrasts = T) %>%
  add_significance_stars(hide_p = F, hide_se = T, hide_ci = F) %>%
  bold_p()

# Plot smooth effects (partial effects)
p <- draw(m1, scales = "fixed")

p & labs(y = "Partial effect",
         x = "Hind tibia length (mm)") 

# Plot predictions of the linear fixed effects
plot_maturation_honey<- plot_model(m1, 
                                   type="pred", 
                                   terms = c("Age"),
                                   title = "",
                                   ci.lvl = 0.95,
                                   colors = "#F8766D") +
  ylab("Egg maturation") +
  xlab("Age (days)") +
  scale_y_continuous(
    limits = c(0.20, 0.50),  # valores en escala de 0 a 1 (porque es proporción)
    breaks = seq(0.20, 0.50, by = 0.10),
    labels = scales::label_percent(accuracy = 1)
  ) +
  theme_classic(base_size = 12, base_family = "sans") +
  theme(axis.title.x = element_text(size=12, face="plain", colour="black"),
        axis.title.y = element_text(size=12, face="plain", colour="black"),
        axis.line.x = element_line(color="black", linewidth=0.3),
        axis.line.y = element_line(color="black", linewidth=0.3),
        plot.title = element_text(size=12, face="bold"),
        panel.spacing = unit(0.9, 'lines'),
        legend.margin = margin(0, 0, 0, -15),
        legend.position = "top")
plot_maturation_honey

ggsave(
  "plot_maturation_honey.pdf",
  plot = last_plot(),
  device = NULL,
  path = NULL,
  scale = 1,
  width = 9,
  height = 8,
  units = "cm",
  dpi = 300,
  limitsize = TRUE,
  bg = NULL,
  create.dir = FALSE
)

# I. Egg resorption rates ####
My_data <- read_excel("Ovigenesis_table.xlsx", 
                      col_types = c("text", "text", "text", 
                                    "text", "text", "text", "numeric", 
                                    "numeric", "numeric", "numeric", 
                                    "numeric", "numeric", "numeric", 
                                    "numeric", "numeric"))
View(My_data)

# Categorical variables to factors
My_data$Age <- factor(My_data$Age)

# Exclude 0, 20 and 25-day-old cohorts
My_data <- subset(My_data, !(Age %in% c(0, 5)))

# Subset for water fed females
My_data <- subset(My_data, Diet == "Honey")
View(My_data)

# Change the reference       
My_data$Age = relevel(My_data$Age, ref = "10")

# Model GAM binomial
Response <- cbind(My_data$Resorbed, My_data$Mature)

r1 <- gam(Response ~ Age + s(Hind_tibia_length, bs = "cr", k = 3), 
          data= My_data, 
          family = binomial(logit))
summary(r1)
anova(r1)

r2 <- gam(Response ~ Age + s(Hind_tibia_length, bs = "cr", 
                             by = Age, k =3), 
          data= My_data, 
          family = binomial(logit))
summary(r2)
anova(r2)

AIC(r1, r2)

dispersion <- sum(residuals(r1, type = "deviance")^2) / r1$df.residual
dispersion

# Fitted model
r1 <- gam(Response ~ Age + s(Hind_tibia_length, bs = "cr", k = 3), 
          data= My_data, 
          family = binomial(logit))
summary(r1)
anova(r1)

# Model checking
# QQplots have to be normal and residuals vs fitted must show no patterns
gam.check(r1, rep=500) # You need a big data set, so 500
appraise(r1, method = "simulate")

# Check for possible outliers
# Cook's Distance
cooks_dist <- cooks.distance(r1)

plot(cooks_dist, type = "h", main = "Cook's Distance", ylab = "Distance", xlab = "Observation")
abline(h = 4 / nrow(My_data), col = "red", lty = 2)

# Deviance residuals
deviance_resid <- residuals(r1, type = "deviance")

plot(deviance_resid, pch = 19, main = "Residuos Deviance", ylab = "Residuals", xlab = "Observation")
abline(h = c(-2, 2), col = "red", lty = 2)

# Which are outliers?
outlier_indices <- which(abs(deviance_resid) > 2)
outlier_indices

# Eliminate the most influential value and run the model again
My_data <- My_data[-c(2),]

# We decided to eliminate this influential value because it corresponds to a
# 10-day-old female which had no resorbed oocytes at this age, uncommon for this age cohort
# (according to results)

# Table of GAM output for Cox final model
gam(Response ~ Age + s(Hind_tibia_length, bs = "cr", k = 3), 
    data= My_data, 
    family = binomial(logit)) %>% 
  tbl_regression(exponentiate = TRUE)

# Get publication ready table and ORs
tbl_regression(r1, exponentiate=T, add_pairwise_contrasts = T) %>%
  add_significance_stars(hide_p = F, hide_se = T, hide_ci = F) %>%
  bold_p()

# Plot smooth effects (partial effects)
p <- draw(r2_q, scales = "fixed")

p & labs(y = "Partial effect",
         x = "Hind tibia length (mm)") 

# Plot predictions of the linear fixed effects
plot_resorption_honey <- plot_model(r1, 
                                    type="pred", 
                                    terms = c("Age"),
                                    title = "",
                                    colors = "#F8766D") +
  ylab("Egg resorption") +
  xlab("Age (days)")
plot_resorption_honey 


# Add a point in 5 day old cohort
pred_data <- plot_model(r1, type = "pred", terms = c("Age"), title = "")$data
pred_data <- as.data.frame(pred_data)

pred_data <- pred_data %>%
  mutate(x_num = case_when(
    x == "5" ~ 5,
    x == "10" ~ 10,
    x == "15" ~ 15,
    x == "20" ~ 20,
    x == "25" ~ 25,
    TRUE ~ NA_real_
  ))

pred_data$x <- NULL

extra_point <- data.frame(
  x_num = 5,
  predicted = 0,
  conf.low = NA,
  conf.high = NA,
  group = NA  # No tiene grupo porque es único
)

plot_data <- bind_rows(pred_data, extra_point)

# Plot
plot_resorption_honey <- ggplot(plot_data, aes(x = x_num, y = predicted)) +
  
  #
  geom_linerange(
    data = pred_data,  # solo donde hay conf.low y conf.high
    aes(ymin = conf.low, ymax = conf.high),
    size = 0.7,
    color = "#F8766D",
    linetype = "solid",
    show.legend = FALSE
  ) +
  
  geom_point(
    data = pred_data,
    aes(color = "Honey"),
    size = 2.48
  ) +
  
  geom_point(
    data = extra_point,
    aes(x = x_num, y = predicted),
    size = 2.48,
    color = "azure4"
  ) +
  
  scale_color_manual(
    name = "Diet",
    values = c("Honey" = "#F8766D")
  ) +
  
  scale_x_continuous(breaks = c(5, 10, 15, 20, 25),
                     labels = c("5", "10", "15", "20", "25")) +
  scale_y_continuous(labels = scales::label_percent(accuracy = 1)) +

  ylab("Egg resorption") +
  xlab("Age (days)") +
  theme(
    legend.position = "none",
    legend.margin = margin(t = 17.5, b = 5),
    aspect.ratio = 0.85,
    plot.margin = margin(t = 5, r = 5, b = 5, l = 5) 
  ) +
  theme_classic(base_size = 12, base_family = "sans") +
  theme(axis.title.x = element_text(size=12, face="plain", colour="black"),
        axis.title.y = element_text(size=12, face="plain", colour="black"),
        axis.line.x = element_line(color="black", linewidth=0.3),
        axis.line.y = element_line(color="black", linewidth=0.3),
        plot.title = element_text(size=12, face="bold"),
        panel.spacing = unit(0.9, 'lines'),
        legend.margin = margin(0, 0, 0, -15),
        legend.position = "none")

plot_resorption_honey

ggsave(
  "plot_resorption_honey.pdf",
  plot = last_plot(),
  device = NULL,
  path = NULL,
  scale = 1,
  width = 9,
  height = 8,
  units = "cm",
  dpi = 300,
  limitsize = TRUE,
  bg = NULL,
  create.dir = FALSE
)

# END