#################################################################################################################################################################
# --------------------------------------------------------------------------------------------------------------------------------------------------------------#
# Supplementary R code for:                                                                                                                                     #
# Exploration behavior differs between Darwin’s finch species and predicts territory defense and hatching success                                               #
# Published in Behavioral Ecology and Sociobiology                                                                                                              #
# Andrew C. Katsis [1,2*], Diane Colombelli-Négrel [1], Çağlar Akçay [3,4], Lauren K. Common [1,2], Jefferson García-Loor [2] & Sonia Kleindorfer [1,2]         #
#     1. College of Science and Engineering, Flinders University, Adelaide, Australia                                                                           #
#     2. Konrad Lorenz Research Center for Behavior and Cognition and Department of Behavioral and Cognitive Biology, University of Vienna, Vienna, Austria     #
#     3. Department of Psychology, Koç University, Istanbul, Turkey                                                                                             #
#     4. School of Life Sciences, Anglia Ruskin University, Cambridge, United Kingdom                                                                           #
#     * corresponding author: andrewckatsis@gmail.com                                                                                                           #
# --------------------------------------------------------------------------------------------------------------------------------------------------------------#
#################################################################################################################################################################

# R packages required for data analysis and figure creation
library(effects) #version 4.2-2
library(car) #version 3.1-1
library(emmeans) #version 1.8.5
library(multcomp) #version 1.4-23
library(lattice) #version 0.20-45
library(gridExtra) #version 2.3
library(grid) #base package
library(ggpubr) #version 0.6.0
library(lmtest) #version 0.9-40
library(MuMIn) #version 1.47.5
library(gtools) #version 3.9.4
library(gdata) #version 2.18.0.1
library(ggplot2) #version 3.4.1
library(plyr) #version 1.8.8
library(dplyr) #version 1.1.1
library(plotrix) #version 3.8-2
library(conflicted) #version 1.2.0
library(ggbeeswarm) #version 0.7.1
library(glmmTMB) #version 1.1.6
library(PCAtest) #version 0.0.1

conflict_prefer("rename", "plyr")

# Import dataset
# Import supplementary data file (sheet: "FinchBehaviorDataset"), naming the dataset "DarwinsFinchBehavior"

# Check number of rows in dataset
nrow(DarwinsFinchBehavior) #275

#####################################################
########## PREPARING BEHAVIORAL VARIABLES ##########
#####################################################

# ----------------------------------------------------------------------------------- #
# ------------- Create separate data sets for each behavioral variable -------------- #
# ----------------------------------------------------------------------------------- #

# Only trials where boldness was measured was measured
DarwinsFinchBoldness <- subset(DarwinsFinchBehavior, MeasuredBoldness == "Y")
nrow(DarwinsFinchBoldness) #275

# Only trials where exploration was measured
DarwinsFinchExploration <- subset(DarwinsFinchBehavior, MeasuredExploration == "Y")
nrow(DarwinsFinchExploration) #162

# Only trials where aggressiveness was measured
DarwinsFinchAggressiveness <- subset(DarwinsFinchBehavior, MeasuredAggressiveness == "Y")
nrow(DarwinsFinchAggressiveness) # 161

# ----------------------------------------------------------------------------------- #
# ------------------------ Make behavioral variables numeric ------------------------ #
# ----------------------------------------------------------------------------------- #

# Make 'unique sector visits' numeric
DarwinsFinchExploration$Exploration_UniqueSectorVisits <- as.numeric(as.character(DarwinsFinchExploration$Exploration_UniqueSectorVisits))
# Make 'total sector visits' numeric
DarwinsFinchExploration$Exploration_SectorVisits <- as.numeric(as.character(DarwinsFinchExploration$Exploration_SectorVisits))

# ----------------------------------------------------------------------------------- #
# --- Remove cactus finches (CF) and hybrid tree finches (HTF) from all datasets ---- #
# ----------------------------------------------------------------------------------- #

# Remove CF and HTF from exploration dataset
nrow(DarwinsFinchExploration) #162
DarwinsFinchExplorationMain <- subset(DarwinsFinchExploration, Species!="CF" & Species!="Hybrid TF")
nrow(DarwinsFinchExplorationMain) #152

# Remove CF and HTF from aggressiveness dataset
nrow(DarwinsFinchAggressiveness) #161
DarwinsFinchAggressivenessMain <- subset(DarwinsFinchAggressiveness, Species!="CF" & Species!="Hybrid TF")
nrow(DarwinsFinchAggressivenessMain) #151

# Remove CF and HTF from boldness dataset
nrow(DarwinsFinchBoldness) #275
DarwinsFinchBoldnessMain <- subset(DarwinsFinchBoldness, Species!="CF" & Species!="Hybrid TF")
nrow(DarwinsFinchBoldnessMain) #262

# ------------------------------------------------------ #
# ------------ Create PC_Exploration variable----------- #
# ------------------------------------------------------ # 

# Confirm significant correlation between 'total sector visits' and 'unique sector visits'

cor.test(DarwinsFinchExplorationMain$Exploration_SectorVisits, DarwinsFinchExplorationMain$Exploration_UniqueSectorVisits, method="spearman", exact=FALSE)

# Use PCA to combine 'total sector visits' and 'unique sector visits', retain only one principal component (PC_Exploration) 

local({
  .PC <- princomp(~ Exploration_SectorVisits + Exploration_UniqueSectorVisits, cor=TRUE, 
  data=DarwinsFinchExplorationMain)
  cat("\nComponent loadings:\n")
  print(unclass(loadings(.PC)))
  cat("\nComponent variances:\n")
  print(.PC$sd^2)
  cat("\n")
  print(summary(.PC))
  screeplot(.PC)
  DarwinsFinchExplorationMain <<- within(DarwinsFinchExplorationMain, {
  PC_Exploration <- .PC$scores[,1]
  })
})

#############################
########## RESULTS ##########
#############################

####################################################################################
# ---------------------------------------------------------------------------------#
# Part A: Between-species differences in boldness, exploration, and aggressiveness #
# ---------------------------------------------------------------------------------#
####################################################################################

# ----------------------------------------------------------------------------------- #
# ------------------------- Species differences in boldness ------------------------- #
# ----------------------------------------------------------------------------------- #

# Conduct ANOVAs to test whether 'Species' significantly predicts behavioral variable
# If 'Species' is significant, conduct post hoc pairwise comparisons between Darwin's finch species

nrow(DarwinsFinchBoldnessMain) #262
DarwinsFinchBoldnessMain$Species = relevel(DarwinsFinchBoldnessMain$Species, ref="SGF")

### Processing response, zero-inflated Poisson GLM
Model.1a <- glmmTMB(Boldness_ProcessingResponse ~ Sex + Species + Boldness_HandlerID, ziformula = ~1, , data = DarwinsFinchBoldnessMain,  family=poisson)
Anova(Model.1a, type = 2)
multi <- emmeans(Model.1a, ~ Species)
pairs(multi, adjust="holm") # posthoc pairwise comparisons

### Back-test response, zero-inflated Poisson GLM
Model.1b <- glmmTMB(Boldness_BackTestResponse ~ Sex + Species + Boldness_HandlerID, ziformula= ~1, data = DarwinsFinchBoldnessMain, family=poisson)
summary(Model.1b)
Anova(Model.1b, type = 2)
multi <- emmeans(Model.1b, ~ Species)
pairs(multi, adjust="holm") # posthoc pairwise comparisons

# ----------------------------------------------------------------------------------- #
# ------------------------ Species differences in exploration ----------------------- #
# ----------------------------------------------------------------------------------- #

# Conduct ANOVAs to test whether 'Species' significantly predicts behavioral variable
# If 'Species' is significant, conduct post hoc pairwise comparisons between Darwin's finch species

### PC_Exploration, linear model

Model.2a <- lm(PC_Exploration ~ Sex + Species, data=DarwinsFinchExplorationMain)
Anova(Model.2a, type=2) #ANOVA
multi <- emmeans(Model.2a, ~ Species)
pairs(multi, adjust="holm")

###### For supplementary material: Species differences in 'floor use'

# Floor use, binomial GLM
Model.2b <- glm(Exploration_FloorUse ~ Sex + Species, data=DarwinsFinchExplorationMain, family=binomial(link="logit"))
Anova(Model.2b, type=2)
multi <- emmeans(Model.2b, ~ Species)
pairs(multi, adjust="holm")

###### For supplementary material: Species differences in 'total sector visits' only

# Cube-root-transform total sector visits to normalise model residuals
DarwinsFinchExplorationMain$Exploration_SectorVisitsCR <- (DarwinsFinchExplorationMain$Exploration_SectorVisits)^(1/3)

Model.2c <- lm(Exploration_SectorVisitsCR ~ Sex + Species, data=DarwinsFinchExplorationMain)
Anova(Model.2c, type=2)
multi <- emmeans(Model.2c, ~ Species)
pairs(multi, adjust="holm")

# ----------------------------------------------------------------------------------- #
# ---------------------- Species differences in aggressiveness ---------------------- #
# ----------------------------------------------------------------------------------- #

# Conduct ANOVAs to test whether 'Species' significantly predicts behavioral variable
# 'Species' is not significant, so we do not conduct post hoc pairwise comparisons

# Make 'Time Near Mirror' a numerical variable
DarwinsFinchAggressivenessMain$Aggressiveness_TimeNearMirror <- as.numeric(as.character(DarwinsFinchAggressivenessMain$Aggressiveness_TimeNearMirror))

Model.3a <- glm(Aggressiveness_AttackedMirror ~ Sex + Species, data=DarwinsFinchAggressivenessMain, family=binomial(link="logit"))
Anova(Model.3a, type=2) # No significant effect of species or sex on aggressiveness (attacked mirror)

Model.3b <- glmmTMB(Aggressiveness_TimeNearMirror^0.5 ~ Sex + Species, ziformula = ~Species, data = DarwinsFinchAggressivenessMain, family=gaussian)
Anova(Model.3b, type=2) # No significant effect of species or sex on aggressiveness (time near mirror, square-root-transformed)

# ---------------------------------------------------------------------------------------------------------#
# ---------------------------------------------------------------------------------------------------------#
# Part A: For supplementary material: Between-site differences in boldness, exploration and aggressiveness #
# ---------------------------------------------------------------------------------------------------------#
# ---------------------------------------------------------------------------------------------------------#

# ----------------------------------------------------------------------------------- #
# ---------------------- Comparing boldness between study sites --------------------- #
# ----------------------------------------------------------------------------------- #

# -------------------------------------------------- #
# ---- Study site differences in boldness (SGF) ---- #
# -------------------------------------------------- #

# Create dataset with only SGF
nrow(DarwinsFinchBoldnessMain) #262
DarwinsFinchBoldnessMainOnlySGF <- subset (DarwinsFinchBoldnessMain, Species=="SGF")
nrow(DarwinsFinchBoldnessMainOnlySGF) #152

#### PROCESSING RESPONSE

Model.4a <- glmmTMB(Boldness_ProcessingResponse ~ Site + Boldness_HandlerID, ziformula = ~1, data = DarwinsFinchBoldnessMainOnlySGF,  family=poisson)
Anova(Model.4a, type = 2)

#### BACK-TEST RESPONSE

Model.4b <- glmmTMB(Boldness_BackTestResponse ~ Site + Boldness_HandlerID, ziformula = ~1, data = DarwinsFinchBoldnessMainOnlySGF, family=poisson)
Anova(Model.4b, type = 2)

# -------------------------------------------------- #
# ---- Study site differences in boldness (STF) ---- #
# -------------------------------------------------- #

# Create dataset with only STF
nrow(DarwinsFinchBoldnessMain) #262
DarwinsFinchBoldnessMainOnlySTF <- subset (DarwinsFinchBoldnessMain, Species=="STF")
nrow(DarwinsFinchBoldnessMainOnlySTF) #61

#### PROCESSING RESPONSE

Model.5a <- glmmTMB(Boldness_ProcessingResponse ~ Site + Boldness_HandlerID, ziformula= ~1, data =DarwinsFinchBoldnessMainOnlySTF,  family=poisson)
Anova(Model.5a , type = 2)

#### BACK-TEST RESPONSE

Model.5b  <- glmmTMB(Boldness_BackTestResponse ~ Site + Boldness_HandlerID, ziformula = ~1, data = DarwinsFinchBoldnessMainOnlySTF, family=poisson)
Anova(Model.5b, type = 2)
multi <- emmeans(Model.5b, ~ Site)
pairs(multi, adjust="holm") # posthoc pairwise comparisons

# -------------------------------------------------- #
# ---- Study site differences in boldness (MTF) ---- #
# -------------------------------------------------- #

# Create dataset with only MTF
nrow(DarwinsFinchBoldnessMain) #262
DarwinsFinchBoldnessMainOnlyMTF <- subset (DarwinsFinchBoldnessMain, Species=="MTF")
nrow(DarwinsFinchBoldnessMainOnlyMTF) #24

#### PROCESSING RESPONSE

Model.6a <- glmmTMB(Boldness_ProcessingResponse ~ Site + Boldness_HandlerID, ziformula = ~1, data = DarwinsFinchBoldnessMainOnlyMTF, family=poisson)
Anova(Model.6a, type = 2)

#### BACK-TEST RESPONSE

Model.6b <- glmmTMB(Boldness_BackTestResponse ~ Site + Boldness_HandlerID, ziformula = ~1, data = DarwinsFinchBoldnessMainOnlyMTF, family=poisson)
Anova(Model.6b, type = 2)
multi <- emmeans(Model.6b, ~ Site)
pairs(multi, adjust="holm") # posthoc pairwise comparisons

# ----------------------------------------------------------------------------------- #
# -------------------- Comparing exploration between study sites -------------------- #
# ----------------------------------------------------------------------------------- #

# ----------------------------------------------------- #
# ---- Study site differences in exploration (SGF) ---- #
# ----------------------------------------------------- #

# Create dataset with only SGF
nrow(DarwinsFinchExplorationMain) #152
DarwinsFinchExplorationMainOnlySGF <- subset (DarwinsFinchExplorationMain, Species=="SGF")
nrow(DarwinsFinchExplorationMainOnlySGF) #75

Model.7 <- lm(PC_Exploration ~ Site, data=DarwinsFinchExplorationMainOnlySGF)
AICc(Model.7)
Anova(Model.7, type=2)

# ----------------------------------------------------- #
# ---- Study site differences in exploration (STF) ---- #
# ----------------------------------------------------- #


# Create dataset with only STF
nrow(DarwinsFinchExplorationMain) #152
DarwinsFinchExplorationMainOnlySTF <- subset (DarwinsFinchExplorationMain, Species=="STF")
nrow(DarwinsFinchExplorationMainOnlySTF) #46

Model.8 <- lm(PC_Exploration ~ Site, data=DarwinsFinchExplorationMainOnlySTF)
AICc(Model.8)
Anova(Model.8, type=2)
multi <- emmeans(Model.8, ~ Site)
pairs(multi, adjust="holm")

# ----------------------------------------------------- #
# ---- Study site differences in exploration (MTF) ---- #
# ----------------------------------------------------- #

# Create dataset with only MTF
nrow(DarwinsFinchExplorationMain) #152
DarwinsFinchExplorationMainOnlyMTF <- subset (DarwinsFinchExplorationMain, Species=="MTF")
nrow(DarwinsFinchExplorationMainOnlyMTF) #21

Model.9 <- lm(PC_Exploration ~ Site, data=DarwinsFinchExplorationMainOnlyMTF)
AICc(Model.9)
Anova(Model.9, type=2)
multi <- emmeans(Model.9, ~ Site)
pairs(multi, adjust="holm")

# ----------------------------------------------------------------------------------- #
# --------- Comparing aggressiveness (time near mirror) between study sites --------- #
# ----------------------------------------------------------------------------------- #

# -------------------------------------------------------- #
# ---- Study site differences in aggressiveness (SGF) ---- #
# -------------------------------------------------------- #

# Create dataset with only SGF
nrow(DarwinsFinchAggressivenessMain) #151
DarwinsFinchAggressivenessMainOnlySGF <- subset (DarwinsFinchAggressivenessMain, Species=="SGF")
nrow(DarwinsFinchAggressivenessMainOnlySGF) #75

Model.10 <- glmmTMB(Aggressiveness_TimeNearMirror ~ Site, ziformula = ~1, data = DarwinsFinchAggressivenessMainOnlySGF,  family=gaussian)
Anova(Model.10, type = 2)

# -------------------------------------------------------- #
# ---- Study site differences in aggressiveness (STF) ---- #
# -------------------------------------------------------- #

# Create dataset with only STF
nrow(DarwinsFinchAggressivenessMain) #151
DarwinsFinchAggressivenessMainOnlySTF <- subset (DarwinsFinchAggressivenessMain, Species=="STF")
nrow(DarwinsFinchAggressivenessMainOnlySTF) #45

Model.11 <- glmmTMB(Aggressiveness_TimeNearMirror ~ Site, ziformula = ~1, data = DarwinsFinchAggressivenessMainOnlySTF,  family=gaussian)
Anova(Model.11, type = 2)

# -------------------------------------------------------- #
# ---- Study site differences in aggressiveness (MTF) ---- #
# -------------------------------------------------------- #

# Create dataset with only MTF
nrow(DarwinsFinchAggressivenessMain) #151
DarwinsFinchAggressivenessMainOnlyMTF <- subset (DarwinsFinchAggressivenessMain, Species=="MTF")
nrow(DarwinsFinchAggressivenessMainOnlyMTF) #21

Model.12 <- glmmTMB(Aggressiveness_TimeNearMirror ~ Site, ziformula = ~1, data = DarwinsFinchAggressivenessMainOnlyMTF,  family=gaussian)
Anova(Model.12, type = 2)

# ----------------------------------------------------------------------------#
# ----------------------------------------------------------------------------#
#  Part A: For supplementary material: Correlations between behavioral traits #
# ----------------------------------------------------------------------------#
# ----------------------------------------------------------------------------#

# --------------------------------------------------------------------------------------------- #
# ---- Correlation between boldness variables (back-test response and processing response) ---- #
# --------------------------------------------------------------------------------------------- #

nrow(DarwinsFinchBoldnessMain) #262

# Spearman's tie-adjusted rank correlation
cor.test(DarwinsFinchBoldnessMain$Boldness_ProcessingResponse, DarwinsFinchBoldnessMain$Boldness_BackTestResponse, method="spearman", exact=FALSE)

# --------------------------------------------------------------------------------------------- #
# ---- Relationship between aggressiveness variables (attacked mirror and time near mirror) --- #
# --------------------------------------------------------------------------------------------- #

# Subset that only includes birds with mirror stimulation test
nrow(DarwinsFinchExplorationMain) #152
DarwinsFinchExplorationMainWithMirror <- subset (DarwinsFinchExplorationMain, MeasuredAggressiveness!="N")
nrow(DarwinsFinchExplorationMainWithMirror) #151

# Make 'Time Near Mirror' as numerical variable
DarwinsFinchExplorationMainWithMirror$Aggressiveness_TimeNearMirror <- as.numeric(as.character(DarwinsFinchExplorationMainWithMirror$Aggressiveness_TimeNearMirror))

# Time near mirror vs Attacked mirror
wilcox.test(Aggressiveness_TimeNearMirror ~ Aggressiveness_AttackedMirror, data = DarwinsFinchExplorationMainWithMirror)

# --------------------------------------------------------------------------------------------- #
# -------------------- Relationships between exploration and aggressiveness ------------------- #
# --------------------------------------------------------------------------------------------- #

# --------------------------------------------------------------------------------------- #
# -------------------------- PC_Exploration vs Attacked mirror -------------------------- #
# --------------------------------------------------------------------------------------- #

# All species combined
wilcox.test(PC_Exploration ~ Aggressiveness_AttackedMirror, data = DarwinsFinchExplorationMainWithMirror)

# Create new datasets for each species
DarwinsFinchExplorationMainWithMirror_SGF <- subset(DarwinsFinchExplorationMainWithMirror, Species == "SGF")
nrow(DarwinsFinchExplorationMainWithMirror_SGF) # 75
DarwinsFinchExplorationMainWithMirror_MGF <- subset(DarwinsFinchExplorationMainWithMirror, Species == "MGF")
nrow(DarwinsFinchExplorationMainWithMirror_MGF) # 10
DarwinsFinchExplorationMainWithMirror_STF <- subset(DarwinsFinchExplorationMainWithMirror, Species == "STF")
nrow(DarwinsFinchExplorationMainWithMirror_STF) # 45
DarwinsFinchExplorationMainWithMirror_MTF <- subset(DarwinsFinchExplorationMainWithMirror, Species == "MTF")
nrow(DarwinsFinchExplorationMainWithMirror_MTF) # 21

# Separate tests per species
wilcox.test(PC_Exploration ~ Aggressiveness_AttackedMirror, data = DarwinsFinchExplorationMainWithMirror_SGF)
wilcox.test(PC_Exploration ~ Aggressiveness_AttackedMirror, data = DarwinsFinchExplorationMainWithMirror_MGF)
wilcox.test(PC_Exploration ~ Aggressiveness_AttackedMirror, data = DarwinsFinchExplorationMainWithMirror_STF, exact = FALSE)
wilcox.test(PC_Exploration ~ Aggressiveness_AttackedMirror, data = DarwinsFinchExplorationMainWithMirror_MTF, exact = FALSE)

# --------------------------------------------------------------------------------------- #
# -------------------------- PC_Exploration vs Time Near Mirror ------------------------- #
# --------------------------------------------------------------------------------------- #

# All species combined
# Comparing model fit with and without 'Time near mirror' as a quadratic term
# PC_Exploration vs Time Near Mirror (linear term)
Model.13a <- lm(PC_Exploration ~ Aggressiveness_TimeNearMirror, DarwinsFinchExplorationMainWithMirror)
Anova(Model.13a)

# PC_Exploration vs Time Near Mirror (quadratic term)
Model.13b <- lm(PC_Exploration ~ Aggressiveness_TimeNearMirror + I(Aggressiveness_TimeNearMirror^2), DarwinsFinchExplorationMainWithMirror)
Anova(Model.13b)

# Akaike's Information Criteria (AIC) for linear and quadratic models
AIC(Model.13a, Model.13b) #Model 13a = 512 , Model 13b = 495
# Model.13b (with quadratic term) does a better job explaining our data

# Separate tests per species

# SGF only
# PC_Exploration and Time Near Mirror (quadratic term)
Model.14a <- lm(PC_Exploration ~ Aggressiveness_TimeNearMirror, DarwinsFinchExplorationMainWithMirror_SGF)
Anova(Model.14a)
Model.14b <- lm(PC_Exploration ~ Aggressiveness_TimeNearMirror + I(Aggressiveness_TimeNearMirror^2), DarwinsFinchExplorationMainWithMirror_SGF)
Anova(Model.14b)
AIC(Model.14a, Model.14b) #Quadratic term does improve model fit

# MGF only
Model.15a <- lm(PC_Exploration ~ Aggressiveness_TimeNearMirror, DarwinsFinchExplorationMainWithMirror_MGF)
Anova(Model.15a)
Model.15b <- lm(PC_Exploration ~ Aggressiveness_TimeNearMirror + I(Aggressiveness_TimeNearMirror^2), DarwinsFinchExplorationMainWithMirror_MGF)
Anova(Model.15b)
AIC(Model.15a, Model.15b) #Quadratic term doesn't improve model fit, so we measure correlation using a Spearman's correlation test
cor.test(DarwinsFinchExplorationMainWithMirror_MGF$PC_Exploration, DarwinsFinchExplorationMainWithMirror_MGF$Aggressiveness_TimeNearMirror, method="spearman")

# STF only
Model.16a <- lm(PC_Exploration ~ Aggressiveness_TimeNearMirror, DarwinsFinchExplorationMainWithMirror_STF)
Anova(Model.16a)
Model.16b <- lm(PC_Exploration ~ Aggressiveness_TimeNearMirror + I(Aggressiveness_TimeNearMirror^2), DarwinsFinchExplorationMainWithMirror_STF)
Anova(Model.16b)
AIC(Model.16a, Model.16b) #Quadratic term does improve model fit

# MTF only
Model.17a <- lm(PC_Exploration ~ Aggressiveness_TimeNearMirror, DarwinsFinchExplorationMainWithMirror_MTF)
Anova(Model.17a)
Model.17b <- lm(PC_Exploration ~ Aggressiveness_TimeNearMirror + I(Aggressiveness_TimeNearMirror^2), DarwinsFinchExplorationMainWithMirror_MTF)
Anova(Model.17b)
AIC(Model.17a, Model.17b) #Quadratic term doesn't improve model fit, so we measure correlation using a Spearman's correlation test
cor.test(DarwinsFinchExplorationMainWithMirror_MTF$PC_Exploration, DarwinsFinchExplorationMainWithMirror_MTF$Aggressiveness_TimeNearMirror, method="spearman", exact=FALSE)

# --------------------------------------------------------------------------------------- #
# -------------------- Relationships between exploration and boldness ------------------- #
# --------------------------------------------------------------------------------------- #

# Create separate datasets for each species
DarwinsFinchExplorationMain_SGF <- subset(DarwinsFinchExplorationMain, Species == "SGF")
nrow(DarwinsFinchExplorationMain_SGF) # 75
DarwinsFinchExplorationMain_MGF <- subset(DarwinsFinchExplorationMain, Species == "MGF")
nrow(DarwinsFinchExplorationMain_MGF) # 10
DarwinsFinchExplorationMain_STF <- subset(DarwinsFinchExplorationMain, Species == "STF")
nrow(DarwinsFinchExplorationMain_STF) # 46
DarwinsFinchExplorationMain_MTF <- subset(DarwinsFinchExplorationMain, Species == "MTF")
nrow(DarwinsFinchExplorationMain_MTF) # 21

# ------------------------------------------------------------------------------------------ #
# -------------------------- PC_Exploration vs Back-test response -------------------------- #
# ------------------------------------------------------------------------------------------ #

# All species combined
cor.test(DarwinsFinchExplorationMain$Boldness_BackTestResponse, DarwinsFinchExplorationMain$PC_Exploration, method="spearman", exact=FALSE)

# Separate tests per species
cor.test(DarwinsFinchExplorationMain_SGF$Boldness_BackTestResponse, DarwinsFinchExplorationMain_SGF$PC_Exploration, method="spearman", exact=FALSE)
cor.test(DarwinsFinchExplorationMain_MGF$Boldness_BackTestResponse, DarwinsFinchExplorationMain_MGF$PC_Exploration, method="spearman", exact=FALSE)
cor.test(DarwinsFinchExplorationMain_STF$Boldness_BackTestResponse, DarwinsFinchExplorationMain_STF$PC_Exploration, method="spearman", exact=FALSE)
cor.test(DarwinsFinchExplorationMain_MTF$Boldness_BackTestResponse, DarwinsFinchExplorationMain_MTF$PC_Exploration, method="spearman", exact=FALSE)

# ------------------------------------------------------------------------------------------- #
# -------------------------- PC_Exploration vs Processing response -------------------------- #
# ------------------------------------------------------------------------------------------- #

# All species combined
cor.test(DarwinsFinchExplorationMain$Boldness_ProcessingResponse, DarwinsFinchExplorationMain$PC_Exploration, method="spearman", exact=FALSE)

# Separate tests per species
cor.test(DarwinsFinchExplorationMain_SGF$Boldness_ProcessingResponse, DarwinsFinchExplorationMain_SGF$PC_Exploration, method="spearman", exact=FALSE)
cor.test(DarwinsFinchExplorationMain_MGF$Boldness_ProcessingResponse, DarwinsFinchExplorationMain_MGF$PC_Exploration, method="spearman", exact=FALSE)
cor.test(DarwinsFinchExplorationMain_STF$Boldness_ProcessingResponse, DarwinsFinchExplorationMain_STF$PC_Exploration, method="spearman", exact=FALSE)
cor.test(DarwinsFinchExplorationMain_MTF$Boldness_ProcessingResponse, DarwinsFinchExplorationMain_MTF$PC_Exploration, method="spearman", exact=FALSE)

#####################################################################################3
# -----------------------------------------------------------------------------------#
#  Part B: Relationship between behavioral traits and territory defense in the wild  #
# -----------------------------------------------------------------------------------#
######################################################################################

# Only include birds with successful playback trial
nrow(DarwinsFinchBoldnessMain) #262
DarwinsFinchBoldnessMainPlayback <- subset(DarwinsFinchBoldnessMain, MeasuredTerritoryDefense == "Y")
nrow(DarwinsFinchBoldnessMainPlayback) #48

# ------------------------------------------------------------ #
# ------------- Creation of PC_Playback variable ------------- #
# ------------------------------------------------------------ #

# Make playback trial response variables numeric
DarwinsFinchBoldnessMainPlayback$Playback_Crosses <- as.numeric(as.character(DarwinsFinchBoldnessMainPlayback$Playback_Crosses))
DarwinsFinchBoldnessMainPlayback$Playback_Flights <- as.numeric(as.character(DarwinsFinchBoldnessMainPlayback$Playback_Flights))
DarwinsFinchBoldnessMainPlayback$Playback_Latency <- as.numeric(as.character(DarwinsFinchBoldnessMainPlayback$Playback_Latency))
DarwinsFinchBoldnessMainPlayback$Playback_MinDist <- as.numeric(as.character(DarwinsFinchBoldnessMainPlayback$Playback_MinDist))
DarwinsFinchBoldnessMainPlayback$Playback_TimeWithin1m <- as.numeric(as.character(DarwinsFinchBoldnessMainPlayback$Playback_TimeWithin1m))
DarwinsFinchBoldnessMainPlayback$Playback_TimeWithin5m <- as.numeric(as.character(DarwinsFinchBoldnessMainPlayback$Playback_TimeWithin5m))
DarwinsFinchBoldnessMainPlayback$Playback_TotalVocalisations <- as.numeric(as.character(DarwinsFinchBoldnessMainPlayback$Playback_TotalVocalisations))

# Principal component analysis (PCA) combining seven playback response variables

local({
  .PC <- princomp(~ Playback_Crosses + Playback_Flights + Playback_Latency + Playback_MinDist + Playback_TimeWithin1m + Playback_TimeWithin5m + Playback_TotalVocalisations, cor=TRUE, data=DarwinsFinchBoldnessMainPlayback)
  cat("\nComponent loadings:\n")
  print(unclass(loadings(.PC)))
  cat("\nComponent variances:\n")
  print(.PC$sd^2)
  cat("\n")
  print(summary(.PC))
  screeplot(.PC)
})

# Create data subset that only includes the seven playback response variables
DarwinsFinchBoldnessMainPlaybackPCA <- dplyr::select(DarwinsFinchBoldnessMainPlayback, c('Playback_Crosses' , 'Playback_Flights' , 'Playback_Latency' , 'Playback_MinDist' , 'Playback_TimeWithin1m' , 'Playback_TimeWithin5m' , 'Playback_TotalVocalisations'))

# Test whether PCA is biologically meaningful for this dataset, using package 'PCAtest'
# Calculate the ψ and φ statistics of the PCA, the distinctness of the first two principal components (eigenvalues), and the significance of the loadings of each variable on these principal components
# Number of bootstrapping iterations = 1000, number of permutations = 1000, significance threshold = 0.05

result <- PCAtest(
  DarwinsFinchBoldnessMainPlaybackPCA,
  nperm = 1000,
  nboot = 1000,
  alpha = 0.05,
  indload = TRUE,
  varcorr = TRUE,
  counter = FALSE,
  plot = TRUE
)

# Significant ψ and φ statistics indicate that PCA is biologically meaningful for this dataset because data have a non-random correlational structure
# Only the first principal component (eigenvalue) is significantly distinct, later principal components are not
# Therefore, we only analyse PC1
# We also exclude 'Number of vocalisations' from the PCA because it doesn't load significantly on PC1

# Principal component analysis (PCA) combining six playback response variables, after excluding 'number of vocalisations': PC1 is retained as 'PC_Playback'

local({
  .PC <- princomp(~ Playback_Crosses + Playback_Flights + Playback_Latency + Playback_MinDist + Playback_TimeWithin1m + Playback_TimeWithin5m, cor=TRUE, data=DarwinsFinchBoldnessMainPlayback)
  cat("\nComponent loadings:\n")
  print(unclass(loadings(.PC)))
  cat("\nComponent variances:\n")
  print(.PC$sd^2)
  cat("\n")
  print(summary(.PC))
  screeplot(.PC)
  DarwinsFinchBoldnessMainPlayback <<- within(DarwinsFinchBoldnessMainPlayback, {
    PC_Playback <- .PC$scores[,1]
  })
})

# ------------------------------------------------------------------------------- #
# ------------- Relationship between boldness and territory defense ------------- #
# ------------------------------------------------------------------------------- #

# Set SGF as reference category
DarwinsFinchBoldnessMainPlayback$Species = relevel(DarwinsFinchBoldnessMainPlayback$Species, ref="SGF")
DarwinsFinchBoldnessMainPlayback$Site = relevel(DarwinsFinchBoldnessMainPlayback$Site, ref="Cerro Pajas")

# Processing response vs PC_Playback
Model.18a <- lm(PC_Playback ~ Species + Site + Boldness_ProcessingResponse + Boldness_HandlerID, data=DarwinsFinchBoldnessMainPlayback)
Anova(Model.18a, type=2)

# Back-test response vs PC_Playback
Model.18b <- lm(PC_Playback ~ Species + Site + Boldness_BackTestResponse + Boldness_HandlerID, data=DarwinsFinchBoldnessMainPlayback)
Anova(Model.18b, type=2)

# ---------------------------------------------------------------------------------- #
# ------------- Relationship between exploration and territory defense ------------- #
# ---------------------------------------------------------------------------------- #

nrow(DarwinsFinchExplorationMain) #152
DarwinsFinchExplorationMainPlayback <- subset(DarwinsFinchExplorationMain, MeasuredTerritoryDefense == "Y")
nrow(DarwinsFinchExplorationMainPlayback) #45

#### Import PC_Playback values from dataset DarwinsFinchBoldnessMainPlayback
DarwinsFinchExplorationMainPlayback <- left_join(DarwinsFinchExplorationMainPlayback, DarwinsFinchBoldnessMainPlayback %>% dplyr::select(BirdID, PC_Playback), by = "BirdID")

# PC_Exploration vs PC_Playback
Model.19 <- lm(PC_Playback ~ Species + Site + PC_Exploration, data=DarwinsFinchExplorationMainPlayback)
Anova(Model.19, type=2)

# ------------------------------------------------------------------------------------- #
# ------------- Relationship between aggressiveness and territory defense ------------- #
# ------------------------------------------------------------------------------------- #

# Make 'Time near mirror' a numeric variable
DarwinsFinchExplorationMainPlayback$Aggressiveness_TimeNearMirror <- as.numeric(as.character(DarwinsFinchExplorationMainPlayback$Aggressiveness_TimeNearMirror))

# Aggressiveness (time near mirror) vs PC_Playback
Model.20a <- lm(PC_Playback ~ Species + Site + Aggressiveness_TimeNearMirror, data=DarwinsFinchExplorationMainPlayback)
Anova(Model.20a, type=2)

# Aggressiveness (attacked mirror) vs PC_Playback
Model.20b <- lm(PC_Playback ~ Species + Site + Aggressiveness_AttackedMirror, data=DarwinsFinchExplorationMainPlayback)
Anova(Model.20b, type=2)

#########################################################
# ------------------------------------------------------#
# Part C: Relationship between exploration and fitness  #
# ------------------------------------------------------#
#########################################################

# Males only
nrow(DarwinsFinchExplorationMain) #152
DarwinsFinchExplorationMainMalesOnly <- subset(DarwinsFinchExplorationMain, Sex == "M")
nrow(DarwinsFinchExplorationMainMalesOnly) #125

# Only birds with known pairing status
nrow(DarwinsFinchExplorationMainMalesOnly) #125
DarwinsFinchExplorationMainMalesOnlyPairingStatus <- subset(DarwinsFinchExplorationMainMalesOnly, PairingStatus != "na")
nrow(DarwinsFinchExplorationMainMalesOnlyPairingStatus) #49

# ---------------------------------------------------------------------------------------- #
# ------------- Relationship between PC_Exploration and male pairing success ------------- #
# ---------------------------------------------------------------------------------------- #

# With Species*PC_Exploration interaction
Model.21b <- glm(PairingStatus ~ Species*PC_Exploration, data=DarwinsFinchExplorationMainMalesOnlyPairingStatus, family=binomial)
Anova(Model.21b, type=3) #Interaction not significant

# Without Species*PC_Exploration interaction
Model.21a <- glm(PairingStatus ~ Species + PC_Exploration, data=DarwinsFinchExplorationMainMalesOnlyPairingStatus, family=binomial)
Anova(Model.21a, type=2) #P = 0.067 (visual inspection suggests that non-significant trend is driven by SGF, but Species*PC_Exploration interaction is not significant, see above)

# Compare fit of model with and without interaction
AIC(Model.21b, Model.21a) #models with and without interaction term are not significantly different (AIC 70.0 vs 68.8)

# ------------------------------------------------------------------------------------ #
# ------------- Relationship between PC_Exploration and hatching success ------------- #
# ------------------------------------------------------------------------------------ #

# Limit dataset to paired birds with known nesting outcomes
nrow(DarwinsFinchExplorationMainMalesOnlyPairingStatus) #49
DarwinsFinchExplorationMainMalesOnlyPairingStatusOnlyPaired <- subset(DarwinsFinchExplorationMainMalesOnlyPairingStatus, PairingStatus == "1" & Hatched != "U")
nrow(DarwinsFinchExplorationMainMalesOnlyPairingStatusOnlyPaired) #26

# With Species*PC_Exploration interaction
Model.22a <- glm(Hatched ~ Species*PC_Exploration, data=DarwinsFinchExplorationMainMalesOnlyPairingStatusOnlyPaired, family=binomial)
Anova(Model.22a, type=2)

# Without Species*PC_Exploration interaction
Model.22b <- glm(Hatched ~ Species + PC_Exploration, data=DarwinsFinchExplorationMainMalesOnlyPairingStatusOnlyPaired, family=binomial)
Anova(Model.22b, type=2)

# Compare fit of model with and without interaction
AIC(Model.22b, Model.22a) #model without interaction term has lower AIC (36.0 vs 39.3)

# ------------------------------------------------------------------------------------ #
# ------------- Relationship between PC_Exploration and fledging success ------------- #
# ------------------------------------------------------------------------------------ #

# With Species*PC_Exploration interaction
Model.23a <- glm(Fledged ~ Species*PC_Exploration, data=DarwinsFinchExplorationMainMalesOnlyPairingStatusOnlyPaired, family=binomial)
Anova(Model.23a, type=3)

# Without Species*PC_Exploration interaction
Model.23b <- glm(Fledged ~ Species + PC_Exploration, data=DarwinsFinchExplorationMainMalesOnlyPairingStatusOnlyPaired, family=binomial)
Anova(Model.23b, type=3)

# Compare fit of model with and without interaction
AIC(Model.23b, Model.23a) #model without interaction term has lower AIC (32.0 vs 35.9)

###########################
###########################
######### FIGURES #########
###########################
###########################

######################################################################
#### Figure 2: Graph comparing exploration by species (4 species) ####
######################################################################

DarwinsFinchExplorationMain$Species <- factor(DarwinsFinchExplorationMain$Species,levels = c("SGF", "MGF", "STF", "MTF"))

#+++++++++++++++++++++++++
# Function to calculate the mean and the standard deviation
  # for each group
#+++++++++++++++++++++++++
# data : a data frame
# varname : the name of a column containing the variable
  #to be summarized
# groupnames : vector of column names to be used as
  # grouping variables
data_summary <- function(data, varname, groupnames){
  require(plyr)
  summary_func <- function(x, col){
    c(mean = mean(x[[col]], na.rm=TRUE),
      SEM = ((sd(x[[col]]))/sqrt(length(x[[col]]))), na.rm=TRUE)
  }
  data_sum<-ddply(data, groupnames, .fun=summary_func,
                  varname)
  data_sum <- rename(data_sum, c("mean" = varname))
 return(data_sum)
}

df3 <- data_summary(DarwinsFinchExplorationMain, varname="PC_Exploration", 
                    groupnames=c("Species"))
df3$Species=as.factor(df3$Species)
head(df3)

mean_data <- group_by(DarwinsFinchExplorationMain, Species) %>%
             plyr::summarise(PC_Exploration = mean(PC_Exploration, na.rm = TRUE))

Dots <- ggplot(DarwinsFinchExplorationMain, aes(x=factor(Species), y=PC_Exploration)) + geom_beeswarm(size = 3, shape = 21, fill = "gray", cex = 2.3) +
theme(panel.border = element_blank(), panel.background = element_rect(fill="white"), panel.grid.major = element_blank(),
panel.grid.minor = element_blank(), axis.line = element_line(colour = "black"),
axis.title.x = element_text(colour="black", size=16),
axis.title.y = element_text(colour="black", size=16)) +
labs(x="Species", y="PC_Exploration") + theme(axis.text.x= element_text(colour="black", size=16),
axis.text.y= element_text(colour="black", size=16), legend.title=element_text(size=15), 
    legend.text=element_text(size=15), legend.key.size = unit(3,"line")) + coord_cartesian(ylim=c(-2, 6)) + 
    scale_y_continuous(breaks=seq(-2, 6, 1)) +
annotate("text", x=2, y=5.45, label= "italic(P) < 0.001", size=3, parse=TRUE) + annotate("text", x=2.5, y=4.45, label= "italic(P) == 0.007", size=3, parse=TRUE) + annotate("text", x=2.5, y=5.95, label= "italic(P) < 0.001", size=3, parse=TRUE) +
annotate("text", x=3, y=4.95, label= "italic(P) == 0.034", size=3, parse=TRUE) +
annotate("segment", x = 1, xend = 3, y = 5.25, yend = 5.25) + annotate("segment", x = 2, xend = 3, y = 4.25, yend = 4.25) + annotate("segment", x = 1, xend = 4, y = 5.75, yend = 5.75) +
annotate("segment", x = 2, xend = 4, y = 4.75, yend = 4.75)

A4 <- Dots + geom_point(data=df3, aes(x = Species, y = PC_Exploration), shape=16, size=3, colour="red") + geom_errorbar(data=df3, aes(x = Species, ymin=PC_Exploration-SEM, ymax=PC_Exploration+SEM), width=.20, linewidth=1.2, colour="red")

#Save plot
ggsave(file="Figure2_ExplorationBySpecies.pdf", dpi = 200, width = 15, height = 15, units = c("cm"))

###################################################################
#### Figure 3: Exploration vs territory defense (PC_Playback) #####
###################################################################

ggplot(DarwinsFinchExplorationMainPlayback, aes(x=PC_Exploration, y=PC_Playback)) + geom_smooth(method = "lm", se=FALSE, aes(color=Species, linetype=Species), lwd=1.2) +
geom_jitter(aes(color=Species, fill=Species, shape=Species), color="black", size=4, width=0, height=0, stroke=0.7) +
scale_shape_manual(breaks = c("SGF", "STF", "MTF"), values=c(21:23), labels = c('Small ground finch', 'Small tree finch', 'Medium tree finch')) +
scale_fill_manual(breaks = c("SGF", "STF", "MTF"), values=c("black", "grey75", "grey40"), labels = c('Small ground finch', 'Small tree finch', 'Medium tree finch')) +
scale_color_manual(breaks = c("SGF", "STF", "MTF"), values=c("black", "grey75", "grey40"), labels = c('Small ground finch', 'Small tree finch', 'Medium tree finch')) +
scale_linetype_manual(breaks = c("SGF", "STF", "MTF"), values=c("solid", "dashed", "dotted"), labels = c('Small ground finch', 'Small tree finch', 'Medium tree finch')) +
theme(panel.border = element_blank(), panel.background = element_rect(fill="white"), panel.grid.major = element_blank(),
panel.grid.minor = element_blank(), axis.line = element_line(colour = "black"),
axis.title.x = element_text(colour="black", size=20),
axis.title.y = element_text(colour="black", size=20)) +
labs(x="Exploration\n(PC_Exploration)", y="Response to playback\n(PC_Playback)") +
theme(axis.text.x= element_text(colour="black", size=20),
axis.text.y= element_text(colour="black", size=20), legend.text=element_text(size=16),
legend.key.width = unit(4,"line"), legend.key.height = unit(2,"line"), legend.key= element_rect(fill = NA, color = "NA"), legend.box.background = element_rect(colour = "black", linewidth=2.5), legend.margin = margin(-0.2, 0.2, 0, 0, "cm"), legend.title=element_blank()) +
coord_cartesian(xlim=c(-2,3)) + scale_x_continuous(breaks=seq(-2, 3, 1)) + coord_cartesian(ylim=c(-5, 4)) +
scale_y_continuous(breaks=seq(-4, 4, 2)) + guides(color = guide_legend(keyheight=0.5), default.unit="cm")

#Save plot
ggsave(file="Figure3_ExplorationAndTerritoryDefense.pdf", dpi = 200, width = 25, height = 15, units = c("cm"))

###################################################
#### Figure 4: Exploration vs breeding success ####
###################################################

# ------------------------------------------------------------------ #
# ------------- Fig. 4a: Exploration vs pairing status ------------- #
# ------------------------------------------------------------------ #

#set order of species and fitness categories
FinchSpecies <- c("Small ground finch","Small tree finch","Medium tree finch")
names(FinchSpecies) <- c("SGF", "STF", "MTF")
level_order <- c('MTF','STF','SGF')
level_order2 <- c('yes','no')

DarwinsFinchExplorationMainMalesOnlyPairingStatus$PairingStatusNames <- DarwinsFinchExplorationMainMalesOnlyPairingStatus$PairingStatus
levels(DarwinsFinchExplorationMainMalesOnlyPairingStatus$PairingStatusNames)
levels(DarwinsFinchExplorationMainMalesOnlyPairingStatus$PairingStatusNames) <- c("no", "yes", "na", "U")

F1 <- ggplot(DarwinsFinchExplorationMainMalesOnlyPairingStatus, aes(x=PC_Exploration, y=factor(Species, level = level_order), group=factor(PairingStatusNames, level=level_order2))) +
geom_jitter(position=position_dodge(0.5), size = 3.5, shape = 21, aes(fill = PairingStatusNames), stroke=1.05) + scale_fill_manual(values=c("darkgrey", "white")) +
theme(panel.border = element_blank(), panel.background = element_rect(fill="white"), panel.grid.major = element_blank(),
panel.grid.minor = element_blank(), axis.line = element_line(colour = "black"),
axis.title.x = element_text(colour="black", size=18),
axis.title.y = element_text(colour="black", size=18)) +
labs(x="Male exploration\n(PC_Exploration)", y="Species") +
theme(axis.text.x= element_text(colour="black", size=14),
axis.text.y= element_text(colour="black", size=16), legend.text=element_text(size=16),
legend.position="top", legend.title=element_text(size=16), legend.box.background = element_rect(colour = "black", linewidth=1.5), legend.key=element_blank()) +
guides(fill=guide_legend(title="Paired:"))

# -------------------------------------------------------------------- #
# ------------- Fig. 4b: Exploration vs hatching success ------------- #
# -------------------------------------------------------------------- #

DarwinsFinchExplorationMainMalesOnlyPairingStatusOnlyPaired$HatchedNames <- DarwinsFinchExplorationMainMalesOnlyPairingStatusOnlyPaired$Hatched
levels(DarwinsFinchExplorationMainMalesOnlyPairingStatusOnlyPaired$HatchedNames)
levels(DarwinsFinchExplorationMainMalesOnlyPairingStatusOnlyPaired$HatchedNames) <- c("no", "yes", "na", "U")

F2 <- ggplot(DarwinsFinchExplorationMainMalesOnlyPairingStatusOnlyPaired, aes(x=PC_Exploration, y=factor(Species, level = level_order), group=factor(HatchedNames, level=level_order2))) +
geom_jitter(position=position_dodge(0.5), size = 3.5, shape = 21, aes(fill = HatchedNames), stroke=1.05) + scale_fill_manual(values=c("darkgrey", "white")) +
theme(panel.border = element_blank(), panel.background = element_rect(fill="white"), panel.grid.major = element_blank(),
panel.grid.minor = element_blank(), axis.line = element_line(colour = "black"),
axis.title.x = element_text(colour="black", size=18),
axis.title.y = element_text(colour="black", size=18)) +
labs(x="Male exploration\n(PC_Exploration)", y="") +
theme(axis.text.x= element_text(colour="black", size=14),
axis.text.y= element_text(colour="black", size=16), legend.text=element_text(size=16),
legend.position="top", legend.title=element_text(size=16), legend.box.background = element_rect(colour = "black", linewidth=1.5),legend.key=element_blank()) +
guides(fill=guide_legend(title="Hatched offspring:"))

# -------------------------------------------------------------------- #
# ------------- Fig. 4c: Exploration vs fledging success ------------- #
# -------------------------------------------------------------------- #

DarwinsFinchExplorationMainMalesOnlyPairingStatusOnlyPaired$FledgedNames <- DarwinsFinchExplorationMainMalesOnlyPairingStatusOnlyPaired$Fledged
levels(DarwinsFinchExplorationMainMalesOnlyPairingStatusOnlyPaired$FledgedNames)
levels(DarwinsFinchExplorationMainMalesOnlyPairingStatusOnlyPaired$FledgedNames) <- c("no", "yes", "na", "U")

F3 <- ggplot(DarwinsFinchExplorationMainMalesOnlyPairingStatusOnlyPaired, aes(x=PC_Exploration, y=factor(Species, level = level_order), group=factor(FledgedNames, level=level_order2))) +
geom_jitter(position=position_dodge(0.5), size = 3.5, shape = 21, aes(fill = FledgedNames), stroke=1.05) + scale_fill_manual(values=c("darkgrey", "white")) +
theme(panel.border = element_blank(), panel.background = element_rect(fill="white"), panel.grid.major = element_blank(),
panel.grid.minor = element_blank(), axis.line = element_line(colour = "black"),
axis.title.x = element_text(colour="black", size=18),
axis.title.y = element_text(colour="black", size=18)) +
labs(x="Male exploration\n(PC_Exploration)", y="") +
theme(axis.text.x= element_text(colour="black", size=14),
axis.text.y= element_text(colour="black", size=16), legend.text=element_text(size=16),
legend.position="top", legend.title=element_text(size=16), legend.box.background = element_rect(colour = "black", linewidth=1.5), legend.key=element_blank()) +
guides(fill=guide_legend(title="Fledged offspring:"))

# ------------------------------------------------------------ #
# ------------- Combine 3 panels into one figure ------------- #
# ------------------------------------------------------------ #

Panel1 <- ggarrange(F1, F2, F3, ncol=3, nrow=1, common.legend = FALSE, widths = c(1.05,1,1))
Panel2<- annotate_figure(Panel1, top = textGrob("(a)", x = unit(0, "npc"), y   = unit(0.1, "npc"), just=c("left"),
         gp=gpar(col="black", font=3, fontsize=20)))
Panel3<- annotate_figure(Panel2, top = textGrob("(b)", x = unit(0.37, "npc"), y   = unit(-1, "npc"), just=c("left"),
         gp=gpar(col="black", font=3, fontsize=20)))
Panel4<- annotate_figure(Panel3, bottom = textGrob("(c)", x = unit(0.7, "npc"), y   = unit(17.8, "npc"), just=c("left"),
         gp=gpar(col="black", font=3, fontsize=20)))

#Save plot
ggsave(file="Figure4_ExplorationAndFitness.pdf", dpi = 200, width = 37, height = 15, units = c("cm"))

#########################################
#########################################
######### SUPPLEMENTARY FIGURES #########
#########################################
#########################################

#################################################################
#### Figure S1: Histogram for boldness (processing response) ####
#################################################################

df1 <- DarwinsFinchBoldnessMain %>%
  group_by(Species) %>%
 dplyr::summarise(Boldness_ProcessingResponse = mean(Boldness_ProcessingResponse))

ggplot(DarwinsFinchBoldnessMain, aes(x=Boldness_ProcessingResponse)) + geom_histogram(binwidth=1, fill="dark grey", colour="black") + facet_wrap(Species ~ ., labeller=as_labeller(c(`SGF` = "(a) Small ground finch", `STF` = "(d) Small tree finch",`MGF` = "(b) Medium ground finch", `MTF` = "(c) Medium tree finch"))) +
theme(panel.border = element_blank(), panel.background = element_rect(fill="white"), panel.grid.major = element_blank(),
panel.grid.minor = element_blank(), axis.line = element_line(colour = "black"),
axis.title.x = element_text(colour="black", size=15),
axis.title.y = element_text(colour="black", size=15)) +
labs(x="processing response", y="count") + theme(axis.text.x= element_text(colour="black", size=16),
axis.text.y= element_text(colour="black", size=15), legend.title=element_text(size=15), 
    legend.text=element_text(size=15), legend.key.size = unit(3,"line")) + theme(strip.background = element_blank(), strip.text.x = element_text(size = 13), strip.text = element_text(face = "italic")) +
coord_cartesian(xlim=c(-0.5, 5.5)) + scale_x_continuous(breaks=seq(0, 5, 1)) + geom_vline(data = df1, mapping = aes(xintercept = Boldness_ProcessingResponse), linetype="dotted", linewidth=1, colour="red")

#Save plot
ggsave(file="FigureS1_ProcessingResponseHistogram.pdf", dpi = 200, width = 15, height = 15, units = c("cm"))

################################################################
#### Figure S2: Histogram for boldness (back-test response) ####
################################################################

df2 <- DarwinsFinchBoldnessMain %>%
  group_by(Species) %>%
  dplyr::summarise(Boldness_BackTestResponse = mean(Boldness_BackTestResponse))

ggplot(DarwinsFinchBoldnessMain, aes(x=Boldness_BackTestResponse)) + geom_histogram(binwidth=1, fill="dark grey", colour="black") + facet_wrap(Species ~ ., labeller=as_labeller(c(`SGF` = "(a) Small ground finch", `STF` = "(d) Small tree finch",`MGF` = "(b) Medium ground finch", `MTF` = "(c) Medium tree finch"))) +
theme(panel.border = element_blank(), panel.background = element_rect(fill="white"), panel.grid.major = element_blank(),
panel.grid.minor = element_blank(), axis.line = element_line(colour = "black"),
axis.title.x = element_text(colour="black", size=15),
axis.title.y = element_text(colour="black", size=15)) +
labs(x="back-test response", y="count") + theme(axis.text.x= element_text(colour="black", size=16),
axis.text.y= element_text(colour="black", size=16), legend.title=element_text(size=15), 
    legend.text=element_text(size=15), legend.key.size = unit(3,"line")) + theme(strip.background = element_blank(), strip.text.x = element_text(size = 13), strip.text = element_text(face = "italic")) +
coord_cartesian(xlim=c(-0.5, 8.5)) + scale_x_continuous(breaks=seq(0, 8, 1)) + geom_vline(data = df2, mapping = aes(xintercept = Boldness_BackTestResponse), linetype="dotted", linewidth=1, colour="red")

#Save plot
ggsave(file="FigureS2_BackTestResponseHistogram.pdf", dpi = 200, width = 15, height = 15, units = c("cm"))

#######################################################################
#### Figure S3: Graph comparing exploration by species (6 species) ####
#######################################################################

# Re-do PCA to include cactus finches and hybrid tree finches

local({
  .PC <- princomp(~ Exploration_SectorVisits + Exploration_UniqueSectorVisits, cor=TRUE, 
  data=DarwinsFinchExploration)
  cat("\nComponent loadings:\n")
  print(unclass(loadings(.PC)))
  cat("\nComponent variances:\n")
  print(.PC$sd^2)
  cat("\n")
  print(summary(.PC))
  screeplot(.PC)
  DarwinsFinchExploration <<- within(DarwinsFinchExploration, {
  PC_Exploration6Species <- .PC$scores[,1]
  })
})

DarwinsFinchExploration$Species <- factor(DarwinsFinchExploration$Species,levels = c("SGF", "MGF", "CF", "STF", "MTF", "Hybrid TF"))

#+++++++++++++++++++++++++
# Function to calculate the mean and the standard deviation
  # for each group
#+++++++++++++++++++++++++
# data : a data frame
# varname : the name of a column containing the variable
  #to be summarized
# groupnames : vector of column names to be used as
  # grouping variables
data_summary <- function(data, varname, groupnames){
  require(plyr)
  summary_func <- function(x, col){
    c(mean = mean(x[[col]], na.rm=TRUE),
      SEM = ((sd(x[[col]]))/sqrt(length(x[[col]]))), na.rm=TRUE)
  }
  data_sum<-ddply(data, groupnames, .fun=summary_func,
                  varname)
  data_sum <- rename(data_sum, c("mean" = varname))
 return(data_sum)
}

df3 <- data_summary(DarwinsFinchExploration, varname="PC_Exploration6Species", 
                    groupnames=c("Species"))
df3$Species=as.factor(df3$Species)
head(df3)

mean_data <- group_by(DarwinsFinchExploration, Species) %>%
             plyr::summarise(PC_Exploration6Species = mean(PC_Exploration6Species, na.rm = TRUE))

Dots <- ggplot(DarwinsFinchExploration, aes(x=factor(Species), y=PC_Exploration6Species)) + geom_beeswarm(size = 3, shape = 21, fill = "gray", cex = 1.6) +
theme(panel.border = element_blank(), panel.background = element_rect(fill="white"), panel.grid.major = element_blank(),
panel.grid.minor = element_blank(), axis.line = element_line(colour = "black"),
axis.title.x = element_text(colour="black", size=16),
axis.title.y = element_text(colour="black", size=16)) +
labs(x="Species", y="PC_Exploration") + theme(axis.text.x= element_text(colour="black", size=16),
axis.text.y= element_text(colour="black", size=16), legend.title=element_text(size=15), 
    legend.text=element_text(size=15), legend.key.size = unit(3,"line")) + coord_cartesian(ylim=c(-2, 4.2)) + 
    scale_y_continuous(breaks=seq(-2, 4, 1))

A4 <- Dots + geom_point(data=df3, aes(x = Species, y = PC_Exploration6Species), shape=16, size=3, colour="red") + geom_errorbar(data=df3, aes(x = Species, ymin=PC_Exploration6Species-SEM, ymax=PC_Exploration6Species+SEM), width=.20, linewidth=1.2, colour="red")

#Save plot
ggsave(file="FigureS3_ExplorationBySpeciesAll6.pdf", dpi = 200, width = 20, height = 15, units = c("cm"))

#############################################################
#### Figure S4: comparing exploration across study sites ####
#############################################################

HighlandSpecies2 <- c("Small ground finch","Medium ground finch","Small tree finch","Medium tree finch")
names(HighlandSpecies2) <- c("SGF", "MGF", "STF", "MTF")

DarwinsFinchExplorationMain$Site = relevel(DarwinsFinchExplorationMain$Site, ref="Puerto Velazco Ibarra")

#+++++++++++++++++++++++++
# Function to calculate the mean and the standard deviation
  # for each group
#+++++++++++++++++++++++++
# data : a data frame
# varname : the name of a column containing the variable
  #to be summarized
# groupnames : vector of column names to be used as
  # grouping variables
data_summary <- function(data, varname, groupnames){
  require(plyr)
  summary_func <- function(x, col){
    c(mean = mean(x[[col]], na.rm=TRUE),
      SEM = ((sd(x[[col]]))/sqrt(length(x[[col]]))), na.rm=TRUE)
  }
  data_sum<-ddply(data, groupnames, .fun=summary_func,
                  varname)
  data_sum <- rename(data_sum, c("mean" = varname))
 return(data_sum)
}

df3 <- data_summary(DarwinsFinchExplorationMain, varname="PC_Exploration", 
                     groupnames=c("Site", "Species"))
df3$Site=as.factor(df3$Site)
head(df3)

mean_data <- group_by(DarwinsFinchExplorationMain, Site, Species) %>%
             plyr::summarise(PC_Exploration = mean(PC_Exploration, na.rm = TRUE))

Dots <- ggplot(DarwinsFinchExplorationMain, aes(x=factor(Site), y=PC_Exploration, group=Species)) + geom_beeswarm(shape=21, fill="grey", cex=3.5, size=2, stat = "identity") +
scale_colour_manual(values=c("red", "blue"), name="Location", breaks=c("Asilo de la Paz", "Cerro Pajas", "Puerto Velasco Ibarra"), labels=c("Asilo de la Paz", "Cerro Pajas", "Puerto Velasco Ibarra")) +
theme(panel.border = element_blank(), panel.background = element_rect(fill="white"), panel.grid.major = element_blank(),
panel.grid.minor = element_blank(), axis.line = element_line(colour = "black"),
axis.title.x = element_text(colour="black", size=16), axis.title.y = element_text(colour="black", size=14)) +
labs(x="", y="PC_Exploration") + theme(axis.text.x= element_text(colour="black", size=12),
axis.text.y= element_text(colour="black", size=16), legend.title=element_text(size=15), 
    legend.text=element_text(size=15), legend.key.size = unit(3,"line"), panel.spacing = unit(0, "lines"), strip.background = element_blank(), strip.placement = "outside", strip.text.x = element_text(size = 14, colour = "black")) +
coord_cartesian(ylim=c(-2, 4.2)) + scale_x_discrete(labels = c('Puerto\nVelasco\nIbarra','Asilo de\nla Paz','Cerro\nPajas')) +
facet_wrap(factor(Species, levels=c('SGF','MGF','STF','MTF'), labels = c('Small ground finch','Medium ground finch','Small tree finch','Medium tree finch')) ~ . , strip.position = "bottom", scales = "fixed",  labeller = labeller(Species = HighlandSpecies2), nrow = 1) +
geom_vline(aes(xintercept=3.5), linetype="dotted", linewidth=0.5)

dat_text <- data.frame(
  label = c("", "", "P = 0.040", "P = 0.003"),
  Species  = c("SGF", "MGF", "STF", "MTF")) 

data.segm<-data.frame(x=2,y=3.95,xend=3,yend=3.95,Species="STF")
data.segm2<-data.frame(x=2,y=3.95,xend=3,yend=3.95,Species="MTF")

A1 <- Dots + geom_point(data=df3, aes(x = Site, y = PC_Exploration), shape=16, size=3, colour="red", position=position_dodge(1)) +
geom_errorbar(data=df3, aes(x = Site, ymin=PC_Exploration-SEM, ymax=PC_Exploration+SEM), width=.25, linewidth=1, colour="red", position=position_dodge(1)) +
geom_segment(data=data.segm, aes(x=x,y=y,yend=yend,xend=xend),inherit.aes=FALSE, linewidth = 0.7) +
geom_segment(data=data.segm2, aes(x=x,y=y,yend=yend,xend=xend),inherit.aes=FALSE, linewidth = 0.7) +
geom_text(data = dat_text, mapping = aes(x = -Inf, y = -Inf, label = label), hjust = -1.85, vjust   = -29.1)

#Save plot
ggsave(file="FigureS4_ExplorationAcrossSites.pdf", dpi = 200, width = 25, height = 12, units = c("cm"))

######################################################################################
#### Figure S5: Four panels showing relationships between behavioral variables ######
######################################################################################

# ---------------------------------------------------------------------------------------- #
# ------------- Figure S5a: PC_Exploration vs Boldness (processing response) ------------- #
# ---------------------------------------------------------------------------------------- #

S5_A1 <- ggplot(DarwinsFinchExplorationMain, aes(x=Boldness_ProcessingResponse, y=PC_Exploration)) + geom_beeswarm(size = 3, shape = 21, fill = "gray", cex=1.9) +
geom_smooth(method = "lm", se=FALSE) +
theme(panel.border = element_blank(), panel.background = element_rect(fill="white"), panel.grid.major = element_blank(),
panel.grid.minor = element_blank(), axis.line = element_line(colour = "black"),
axis.title.x = element_text(colour="black", size=18),
axis.title.y = element_text(colour="black", size=18)) +
labs(x="Processing response\n", y="\nPC_Exploration") + theme(axis.text.x= element_text(colour="black", size=18),
axis.text.y= element_text(colour="black", size=18), legend.title=element_text(size=16), 
    legend.text=element_text(size=16), legend.key.size = unit(3,"line")) + coord_cartesian(xlim=c(0, 5)) + 
    scale_x_continuous(breaks=seq(0, 5, 1)) + coord_cartesian(ylim=c(-2, 4.3)) + 
    scale_y_continuous(breaks=seq(-2, 4, 1))

# --------------------------------------------------------------------------------------- #
# ------------- Figure S5a: PC_Exploration vs Boldness (back test response) ------------- #
# --------------------------------------------------------------------------------------- #

S5_A2 <- ggplot(DarwinsFinchExplorationMain, aes(x = Boldness_BackTestResponse, y=PC_Exploration)) + geom_beeswarm(size = 3, shape = 21, fill = "gray", cex=1.9) +
#geom_smooth(method = "lm", se=FALSE) +
theme(panel.border = element_blank(), panel.background = element_rect(fill="white"), panel.grid.major = element_blank(),
panel.grid.minor = element_blank(), axis.line = element_line(colour = "black"),
axis.title.x = element_text(colour="black", size=18),
axis.title.y = element_text(colour="black", size=18)) +
labs(x="Back-test response\n", y="\nPC_Exploration") + theme(axis.text.x= element_text(colour="black", size=18),
axis.text.y= element_text(colour="black", size=18), legend.title=element_text(size=16), 
    legend.text=element_text(size=16), legend.key.size = unit(3,"line")) + coord_cartesian(xlim=c(0, 8)) + 
    scale_x_continuous(breaks=seq(0, 8, 1)) + coord_cartesian(ylim=c(-2, 4.3)) + 
    scale_y_continuous(breaks=seq(-2, 4, 1))

# ------------------------------------------------------------------------------------------ #
# ------------- Figure S5c: PC_Exploration vs Aggressiveness (attacked mirror) ------------- #
# ------------------------------------------------------------------------------------------ #

#+++++++++++++++++++++++++
# Function to calculate the mean and the standard deviation
  # for each group
#+++++++++++++++++++++++++
# data : a data frame
# varname : the name of a column containing the variable
  #to be summarized
# groupnames : vector of column names to be used as
  # grouping variables
data_summary <- function(data, varname, groupnames){
  require(plyr)
  summary_func <- function(x, col){
    c(mean = mean(x[[col]], na.rm=TRUE),
      SEM = ((sd(x[[col]]))/sqrt(length(x[[col]]))), na.rm=TRUE)
  }
  data_sum<-ddply(data, groupnames, .fun=summary_func,
                  varname)
  data_sum <- rename(data_sum, c("mean" = varname))
 return(data_sum)
}

df3 <- data_summary(DarwinsFinchExplorationMainWithMirror, varname="PC_Exploration", 
                    groupnames=c("Aggressiveness_AttackedMirror"))
df3$Aggressiveness=as.factor(df3$Aggressiveness_AttackedMirror)
head(df3)

mean_data <- group_by(DarwinsFinchExplorationMainWithMirror, Aggressiveness_AttackedMirror) %>%
             plyr::summarise(PC_Exploration = mean(PC_Exploration, na.rm = TRUE))

Dots <- ggplot(DarwinsFinchExplorationMainWithMirror, aes(x=factor(Aggressiveness_AttackedMirror), y=PC_Exploration)) + geom_beeswarm(size = 3, shape = 21, fill = "gray", cex = 2) +
theme(panel.border = element_blank(), panel.background = element_rect(fill="white"), panel.grid.major = element_blank(),
panel.grid.minor = element_blank(), axis.line = element_line(colour = "black"),
axis.title.x = element_text(colour="black", size=18),
axis.title.y = element_text(colour="black", size=18)) +
labs(x="Attacked mirror\n", y="\nPC_Exploration") + theme(axis.text.x= element_text(colour="black", size=18),
axis.text.y= element_text(colour="black", size=18), legend.title=element_text(size=16), 
    legend.text=element_text(size=16), legend.key.size = unit(3,"line")) + coord_cartesian(ylim=c(-2, 5)) + 
    scale_y_continuous(breaks=seq(-2, 4, 1)) + 
  scale_x_discrete(labels = c('No', 'Yes')) +
annotate("text", x=1.5, y=4.95, label = "italic(P) == 0.018", size=5, parse=TRUE) +
annotate("segment", x = 1, xend = 2, y = 4.65, yend = 4.65) +
annotate("segment", x = 1, xend = 1, y = 4.65, yend = 4.55) +
annotate("segment", x = 2, xend = 2, y = 4.65, yend = 4.55)

S5_A3 <- Dots + geom_point(data=df3, aes(x = Aggressiveness_AttackedMirror, y = PC_Exploration), shape=16, size=3, colour="red") + geom_errorbar(data=df3, aes(x = Aggressiveness_AttackedMirror, ymin=PC_Exploration-SEM, ymax=PC_Exploration+SEM), width=.10, linewidth=1.2, colour="red")

# ------------------------------------------------------------------------------------------- #
# ------------- Figure S5d: PC_Exploration vs Aggressiveness (time near mirror) ------------- #
# ------------------------------------------------------------------------------------------- #

S5_A4 <- ggplot(DarwinsFinchExplorationMainWithMirror, aes(x=Aggressiveness_TimeNearMirror, y=PC_Exploration)) + geom_smooth(method = "lm", formula = y ~ x + I(x^2), se=FALSE, lwd=1.2) +
geom_jitter(shape=21, color="black", size=4, width=0, height=0, stroke=0.7) +
theme(panel.border = element_blank(), panel.background = element_rect(fill="white"), panel.grid.major = element_blank(),
panel.grid.minor = element_blank(), axis.line = element_line(colour = "black"),
axis.title.x = element_text(colour="black", size=20),
axis.title.y = element_text(colour="black", size=20)) +
labs(x="Time near mirror", y="PC_Exploration") +
theme(axis.text.x= element_text(colour="black", size=20),
axis.text.y= element_text(colour="black", size=20), legend.text=element_text(size=16),
legend.key.width = unit(4,"line"), legend.key.height = unit(2,"line"), legend.key= element_rect(fill = NA, color = "NA"), legend.box.background = element_rect(colour = "black", linewidth=2.5), legend.margin = margin(-0.2, 0.2, 0, 0, "cm"), legend.title=element_blank()) +
coord_cartesian(xlim=c(0,180)) + scale_x_continuous(breaks=seq(0, 180, 30)) + coord_cartesian(ylim=c(-2,4.3)) + scale_y_continuous(breaks=seq(-2, 4, 1))

# ------------------------------------------------------------ #
# ------------- Combine 4 panels into one figure ------------- #
# ------------------------------------------------------------ #

Panel1 <- ggarrange(S5_A1,S5_A2,NULL,NULL,S5_A3,S5_A4, ncol=2, nrow=3, common.legend = FALSE, legend="right", heights = c(1,0.10,1,0.1,1))
Panel2<- annotate_figure(Panel1, top = textGrob("(a) Exploration vs boldness (processing)", x = unit(0, "npc"), y   = unit(1.05, "npc"), just=c("left"),
         gp=gpar(col="black", font=3, fontsize=20)))
Panel3<- annotate_figure(Panel2, top = textGrob("(b) Exploration vs boldness (back test)", x = unit(0.50, "npc"), y   = unit(0.05, "npc"), just=c("left"),
         gp=gpar(col="black", font=3, fontsize=20)),  fig.lab.pos="top.right")
Panel4<- annotate_figure(Panel3, bottom = textGrob("(c) Exploration vs aggressiveness (attacked mirror)", x = unit(0, "npc"), y   = unit(17.2, "npc"), just=c("left","top"),
         gp=gpar(col="black", font=3, fontsize=20)))
Panel5<- annotate_figure(Panel4, bottom = textGrob("(d) Exploration vs aggressiveness (time near mirror)", x = unit(0.50, "npc"), y   = unit(17.5, "npc"), just=c("left","bottom"),
         gp=gpar(col="black", font=3, fontsize=20)))

ggsave(file="FigureS5_TraitCorrelations.pdf", dpi = 200, width = 35, height = 27, units = c("cm"))

#############################################################################################
#### Figure S6: Graph comparing exploration (total sector visits) by species (4 species) ####
#############################################################################################

# set order of species categories
DarwinsFinchExplorationMain$Species <- factor(DarwinsFinchExplorationMain$Species,levels = c("SGF", "MGF", "STF", "MTF"))

#+++++++++++++++++++++++++
# Function to calculate the mean and the standard deviation
  # for each group
#+++++++++++++++++++++++++
# data : a data frame
# varname : the name of a column containing the variable
  #to be summarized
# groupnames : vector of column names to be used as
  # grouping variables
data_summary <- function(data, varname, groupnames){
  require(plyr)
  summary_func <- function(x, col){
    c(mean = mean(x[[col]], na.rm=TRUE),
      SEM = ((sd(x[[col]]))/sqrt(length(x[[col]]))), na.rm=TRUE)
  }
  data_sum<-ddply(data, groupnames, .fun=summary_func,
                  varname)
  data_sum <- rename(data_sum, c("mean" = varname))
 return(data_sum)
}

df3 <- data_summary(DarwinsFinchExplorationMain, varname="Exploration_SectorVisitsCR", 
                    groupnames=c("Species"))
df3$Species=as.factor(df3$Species)
head(df3)

mean_data <- group_by(DarwinsFinchExplorationMain, Species) %>%
             plyr::summarise(Exploration_SectorVisitsCR = mean(Exploration_SectorVisitsCR, na.rm = TRUE))

Dots <- ggplot(DarwinsFinchExplorationMain, aes(x=factor(Species), y=Exploration_SectorVisitsCR)) + geom_beeswarm(size = 3, shape = 21, fill = "gray", cex = 2.3) +
theme(panel.border = element_blank(), panel.background = element_rect(fill="white"), panel.grid.major = element_blank(),
panel.grid.minor = element_blank(), axis.line = element_line(colour = "black"),
axis.title.x = element_text(colour="black", size=16),
axis.title.y = element_text(colour="black", size=16)) +
labs(x="Species", y="Total sector visits\n(cube-root)") + theme(axis.text.x= element_text(colour="black", size=16),
axis.text.y= element_text(colour="black", size=16), legend.title=element_text(size=15), 
    legend.text=element_text(size=15), legend.key.size = unit(3,"line")) + coord_cartesian(ylim=c(0, 7.5)) + 
    scale_y_continuous(breaks=seq(0, 7, 1)) +
annotate("text", x=2, y=6.90, label= "italic(P) < 0.001", size=3, parse=TRUE) +
annotate("text", x=2.5, y=6.40, label= "italic(P) == 0.044", size=3, parse=TRUE) +
annotate("text", x=2.5, y=7.40, label= "italic(P) < 0.001", size=3, parse=TRUE) +
annotate("segment", x = 1, xend = 3, y = 6.75, yend = 6.75) +
annotate("segment", x = 2, xend = 3, y = 6.25, yend = 6.25) +
annotate("segment", x = 1, xend = 4, y = 7.25, yend = 7.25)

Dots + geom_point(data=df3, aes(x = Species, y = Exploration_SectorVisitsCR), shape=16, size=3, colour="red") + geom_errorbar(data=df3, aes(x = Species, ymin=Exploration_SectorVisitsCR-SEM, ymax=Exploration_SectorVisitsCR+SEM), width=.20, linewidth=1.2, colour="red")

#Save plot
ggsave(file="FigureS6_ExplorationSectorVisitsBySpecies.pdf", dpi = 200, width = 15, height = 15, units = c("cm"))