############################################################################################################
### This code is to analyse Antarctic biodiversity data in relation to its protection in ASPAs, as published in:
### Wauchope, H. S., Shaw, J., Terauds A. (2019) A snapshot of biodiversity protection in Antarctica. Nature Communications.
### Code is organised into chunks for each figure and supplementary figure in the paper 
### All input should be entered under 'Initialisation'
### All output is printed or saved to figures
### Written by Hannah Wauchope, August-December 2016 and March-Nov 2018, in collaboration with Aleks Terauds and Justine Shaw
### Work conducted under SCAR Service Order "Digitisation of biodiversity records in ASPA Management Plans"
############################################################################################################

##### NOTE: Due to submission requirements, Supplementary Dataset files will need to be converted from .xslx to .csv files for the below code to work ####

#### Initialisation ####
## Load Packages
library(dplyr)
library(ggplot2)
library(reshape)
library(reshape2)
library(rgdal)
library(maptools)
library(extrafont)
library(stringr)
library(scales)
library(rgeos)
library(rgdal)
library(data.table)
library(raster)
library(gstat)
font_import()
loadfonts()

## Create input and output folders (all files are read in from input folder and all figures out written out to output folder)
InputFP <- #Insert input filepath here, ending in a hash, e.g. "/Users/username/Documents/AntarcticaWork/Input/", place source data folder within this folder
OutputFP <- #Insert output filepath here, ending in a hash, e.g. "/Users/username/Documents/AntarcticaWork/Output/"

## Input files
#Data files - These files are available in the 'Source Data' supplementary folder
Desig <- read.csv(paste0(InputFP, "SourceData/ASPADetails.csv"), header=TRUE) #Contains designation data for each ASPA
ChordateCommonNames <- read.csv(paste0(InputFP, "SourceData/ChordateCommonNames.csv")) #This file contains the common names for the chordates
AntarcticData <- read.csv(paste0(InputFP, "SourceData/AntarcticData.csv"))
AntarcticPoints <- read.csv(paste0(InputFP, "SourceData/AntarcticPoints.csv"))
RichnessPoints <- read.csv(paste0(InputFP, "SourceData/RichnessPoints.csv"))
TaxonInfo <- unique(AntarcticData[c("Taxon_ID", "KINGDOM", "PHYLUM", "CLASS", "ORDER", "FAMILY", "GENUS", "SPECIES")])
BackgroundColor <- "#ffffffff"

#Spatial Files - These files are available in supplementary data or online from the Australian Antarctic Data Centre
ASPAPoly <- readOGR(paste0(InputFP, "ASPAs_v4_2018/ASPAs_polygons_v4_2018.shp")) #This file is available as part of supplementary data
ASPAPoly <- ASPAPoly[ASPAPoly$ASPA_No %in% Desig[(Desig$Marine==0),]$ASPA_No,] #Remove marine ASPAs
ASPAPoly <- ASPAPoly[ASPAPoly$NAME!="Sub-surface boundary, Lower Taylor Glacier and Blood Falls, Taylor Valley, McMurdo Dry Valleys",] #remove sub glacial boundary of 172 (doesn't include biodiversity)
ACBRPoly <- readOGR(paste0(InputFP, "ACBRs_v2_2016/ACBRs_v2_2016.shp")) #Shapefile of ACBRs, this file is available from the Australian Antarctic Data Centre
AntPoly <- readOGR(paste0(InputFP, "Coastline_low_res_polygon/Coastline_low_res_polygon.shp")) #Low resolution polygon of Antarctica, this file is available from the Australian Antarctic Data Centre
AntLine <- readOGR(paste0(InputFP, "Coastline_high_res_line/Coastline_high_res_line.shp")) #High resolution outline of Antarctica, this file is available from the Australian Antarctic Data Centre

#Prepare Desig file for analysis
Desig <- subset(Desig, Tot_Area!="De-designated") #Remove de-designated ASPAs
Desig <- Desig[Desig$Marine==0,] #Remove marine ASPAs
Desig$Tot_Area <- NULL #Remove area (as we will calculate from the shapefile instead - in order to not include sub glacial boundary of 172)
ASPAAreas <- dcast(as.data.frame(ASPAPoly), ASPA_No~., sum, value.var="Area_km") #Calculate areas from polygon (from which glacial boundary of 172 is now removed)
names(ASPAAreas) <- c("ASPA_No", "AREA") #Rename
Desig <- merge(Desig, ASPAAreas, by ="ASPA_No") #Add calculated areas in
Desig <- Desig[,c("ASPA_No", "Protocol_designation", "Biodiversity_designated", "AREA", "ACBR_ID")] 
names(Desig) <- c("ASPA_No", "Protocol_designation", "Biodiversity_designated", "AREA", "Desig_ACBR_ID")

#### Figure 1a, Percentage of species protected in each ACBR, and what these represent of all Antarctic species ####
#For each ACBR, find the total number of species and the total number of protected species, and what this represents of the whole Antarctic
ACBRPercentageProt <- rbindlist(lapply(c(1:16), function(ACBR){ #List through the 16 ACBRs and return a dataframe of protection stats
  ACBRData <- subset(AntarcticData, ACBR_ID==ACBR) #Subset to relevant ACBR
  ACBRData <- unique(ACBRData[,c("Taxon_ID", "BinaryProt")]) #For each taxa, get it's binary protection status (this reduces to a long form datatable, but many taxa have some locations within ASPAs and some without, so these will have two entries, one with binaryprot=1 and one where it =0. We must tease these out)
  
  NumTaxa <- length(unique(ACBRData$Taxon_ID))#Get the total number of species (by finding the unique number of taxa)
  
  ProtTaxa <- dcast(ACBRData, Taxon_ID~BinaryProt, value.var="BinaryProt") #Cast the data so that we have the taxa in rows, and a column with showing whether that taxa has some records in ASPAs, (1) and the next for whether the taxa does not (0)
  ProtTaxa[is.na(ProtTaxa)] <- 0
  if(names(ProtTaxa)[2]==0 & ncol(ProtTaxa)==2){ #If there's only two columns and the cast column is '0' this means no species have protection
    ProtTaxa <- 0
  } else {
    ProtTaxa <- nrow(ProtTaxa[ProtTaxa[,3]==1,]) #Subset the data to only taxa that have a 1 in the 1 column (indicates at least some locations protected) and find the number of rows to get the number of taxa
  }

  NumProtTaxa <- as.data.frame(ProtTaxa) #Change values to dataframes for collation
  PercProtTaxa <- as.data.frame(ProtTaxa/NumTaxa)*100 #the percentage of protected taxa is number of protected taxa/total number of taxa
  PercWholeAntTaxa <- as.data.frame(ProtTaxa/length(unique(AntarcticData$Taxon_ID)))*100 #Then find the percentage of taxa protected in the ACBR as a percentage of all Antarctic taxa
  NumTaxa <- as.data.frame(NumTaxa)
  Summary <- cbind(NumTaxa, NumProtTaxa, PercProtTaxa, PercWholeAntTaxa)
  names(Summary) <- c("NumTaxa", "NumProtTaxa", "PercProtTaxa", "PercProtWholeAnt")
  Summary$ACBR <- ACBR
  return(Summary)
}))

#### Figure 1b, Median number of species in each protocol designation ####
#First set up data for plotting (incl. descriptive names of protocol designations, colours for plotting)
Protocol_designation <- c("A", "B", "C", "D", "E", "F", "G", "H", "I")
Description <- c("Inviolate", "Ecosystem", "Species", "Type Locality", "Scientific", "Geological", "Aesthetic", "Historical", "General")
DesigNames <- as.data.frame(cbind(Protocol_designation, Description))
names(DesigNames) <- c("Protocol_designation", "Description")
DesigNames$Description <- factor(DesigNames$Description, levels=DesigNames$Description)
Colours <- c("#acce6aff","#acce6aff","#acce6aff","#acce6aff","#8cb5e0ff","#8cb5e0ff","#acce6aff","#acce6aff","#8cb5e0ff")
ASPATaxa <- unique(subset(AntarcticData, BinaryProt==1)[,c("Taxon_ID", "ASPA_No", "Protocol_designation", "Biodiversity_designated")]) #For protected taxa, get unique records for taxa in ASPAs

#Percentage of protected species in non-biodiversity ASPAs
Nonbiodivtaxa <- dcast(ASPATaxa, Taxon_ID~Biodiversity_designated,length, value.var="Biodiversity_designated") #Cast to find which occur in at least some are biodiversity designated ASPAs
Nonbiodivtaxa <- Nonbiodivtaxa[Nonbiodivtaxa[,3]==0,] #Subset to taxa that have no occurrences in biodiversity designated ASPAs
PercentNonBiodivSpecies <- nrow(Nonbiodivtaxa)/length(unique(ASPATaxa$Taxon_ID)) #Percentage of protected species not in biodiversity ASPAs

#Median number of species per ASPA
NumTaxaPerASPA <- dcast(ASPATaxa, ASPA_No +  Protocol_designation~.,length, value.var="Taxon_ID") #Find the number of taxa in each ASPA
names(NumTaxaPerASPA) <- c("ASPA_No","Protocol_designation", "NumTaxa")

NumTaxaPerASPA <- merge(NumTaxaPerASPA, DesigNames, by="Protocol_designation", all=TRUE) #Add in designation names
NumTaxaPerASPA$Protocol_designation <- as.character(NumTaxaPerASPA$Protocol_designation)
NumTaxaPerASPA <- NumTaxaPerASPA[order(NumTaxaPerASPA$Protocol_designation),] #Order from designations A-H
NumTaxaPerASPA$Description <- factor(NumTaxaPerASPA$Description, levels = unique(NumTaxaPerASPA$Description)) #Make the description a factor so it's ordered correctly in plot
NumTaxaPerASPA[is.na(NumTaxaPerASPA)] <- 0
NumTaxaPerASPA[NumTaxaPerASPA$ASPA_No==0,]$NumTaxa <- NA

MedianwithPointsDesigPlot <- ggplot(data=NumTaxaPerASPA,aes(x=Description, y=NumTaxa, fill=Protocol_designation))+ #Plots mean number of species at each designation
  geom_bar(stat = "summary", fun.y = "median")+
  geom_point(colour="#686868ff", shape=19, size=0.8)+
  coord_flip()+
  scale_fill_manual(values=Colours)+
  scale_y_continuous(expand = c(0.01, 0))+
  scale_x_discrete(expand = c(0.07, 0))+
  ylab("Median number of species")+
  xlab("Reason for designation")+
  theme(panel.background = element_rect(fill = BackgroundColor), plot.background = element_rect(fill = BackgroundColor),
        panel.grid = element_blank(), axis.ticks.y = element_blank(), axis.line = element_line(colour = "#2e5f8cff"),
        axis.ticks.x = element_blank(), plot.margin =unit(c(5,5,5,5),"mm"), legend.spacing = unit(c(0,0,0,0),"mm"),
        text = element_text(size=10, family="Helvetica Neue"), legend.position="none", axis.title.x=element_text(colour="#2e5f8cff", margin=margin(10,0,0,0)), 
        axis.title.y=element_text(colour="#2e5f8cff", margin=margin(0,10,0,0)), axis.text.x=element_text(colour="#2e5f8cff", size=10, family="Helvetica Neue"), axis.text.y=element_text(colour="#2e5f8cff", size=10, family="Helvetica Neue"))

tiff(paste0(OutputFP, '1b_DesigMedian.tiff'), width = 1800, height = 2600, units = "px", res=500)
MedianwithPointsDesigPlot
dev.off()

#### Figure 1c, Top ten species stats ####
#So, need to find out how many ASPAs each species occurs in
TopTens <- rbindlist(lapply(c("Chordates", "PlantLichen", "Inverts"), function (x){ #List through the 3 categories (Chordates, PlantLichen and Invertebrates) and return the ten taxa in each occuring in the most ASPAs
  if(x=="Chordates"){
    TaxaData <- unique(subset(AntarcticData, PHYLUM=="Chordata" & BinaryProt==1)[,c("Taxon_ID", "ASPA_No")]) #Get the unique taxa in each ASPA
  } else if(x=="PlantLichen"){
    TaxaData <- unique(subset(AntarcticData, KINGDOM=="Fungi" | KINGDOM=="Plantae" & BinaryProt==1)[,c("Taxon_ID", "ASPA_No")])
  } else {
    TaxaData <- unique(subset(AntarcticData, KINGDOM=="Animalia" & PHYLUM!="Chordata" & BinaryProt==1)[,c("Taxon_ID", "ASPA_No")])
  }
  
  NumAspas <- dcast(TaxaData, Taxon_ID~., length, value.var="ASPA_No") #Cast to find the number ASPAs each taxa occur in
  names(NumAspas) <- c("Taxon_ID", "NumASPAs")
  NumAspas <- merge(NumAspas, TaxonInfo, by="Taxon_ID") #Add taxonomic information about each taxa
  NumAspas <- head(NumAspas[order(NumAspas$NumASPAs, decreasing=TRUE),],10) #Select the top ten most protected species
  NumAspas$Group <- x
  return(NumAspas)
}))

TopTens <- merge(TopTens, ChordateCommonNames, by="Taxon_ID", all=TRUE) #Add chordate common names
TopTens <- TopTens[!is.na(TopTens$NumASPAs),] #Remove NAs (from the chordates not occurring in the Top ten)
TopTens$Name <- ifelse(is.na(TopTens$CommonName), paste(TopTens$GENUS, TopTens$SPECIES, sep=" "), paste(TopTens$CommonName)) #Paste names together to create a 'name' column, common names for chordates and scientific names for PlantLichen and invertebrates

TopNumGraph <- round_any(max(TopTens$NumASPAs), 10) #Get the maximum number of ASPAs any taxa occurs in, to set the upper x limit of the plot

GraphTheTaxa <- rbindlist(lapply(c("Chordates", "PlantLichen", "Inverts"), function(TaxGroup){
  GraphTheTaxa <- subset(TopTens, Group==TaxGroup)
  GraphTheTaxa <- GraphTheTaxa[order(GraphTheTaxa$NumASPAs)] #Order so the most protected species are listed first
  GraphTheTaxa$Name <- factor(GraphTheTaxa$Name, levels = GraphTheTaxa$Name) #Put the names as factors so they are plotted in the right order
  return(GraphTheTaxa)
})) #Organise the data with factors etc
GraphTheTaxa$Group <- factor(GraphTheTaxa$Group, levels=unique(GraphTheTaxa$Group))
TaxaTopTen <- ggplot(GraphTheTaxa, aes(x=Name, y=NumASPAs))+ #Create the ggplot NOTE it was not possible to get ggplot to italicise species names and not common names, so this needs to be done manually post export
  coord_flip()+
  facet_wrap(GraphTheTaxa$Group, scales = "free_y")+
  geom_bar(fill="#9DC3E6", stat="identity")+
  xlab("Species")+
  ylab("Number of ASPAs in which the species occurs")+
  scale_y_continuous(expand = c(0.03, 0), breaks=pretty_breaks(), limits = c(0, TopNumGraph))+
  scale_x_discrete(expand = c(0.06, 0))+
  theme(panel.background = element_rect(fill = BackgroundColor), plot.background = element_rect(fill = BackgroundColor),
        panel.grid = element_blank(), axis.ticks.y = element_blank(),
        axis.ticks.x = element_blank(), plot.margin =unit(c(5,5,5,5),"mm"), legend.spacing = unit(c(0,0,0,0),"mm"),
        axis.title.x=element_blank(), 
        axis.title.y=element_text(colour="#2e5f8cff", size=11, family="Helvetica Neue"), 
        axis.text.x=element_text(colour="#2e5f8cff", size=11, family="Helvetica Neue"), 
        axis.text.y=element_text(colour="#2e5f8cff", hjust=1, size=11, family="Helvetica Neue", face="italic"),
        axis.line = element_line(colour = "#2e5f8cff"),
        strip.text = element_blank(),
        legend.position="none")
tiff(paste0(OutputFP, '1c_TopTenGraph.tiff'), width = 4500, height = 2000, units = "px", res=500)
TaxaTopTen
dev.off()

### Number of species only found in 1 ASPA
TaxaData <- unique(subset(AntarcticData, BinaryProt==1)[,c("Taxon_ID", "ASPA_No")]) #Find unique taxa occurring in each ASPA
NumASPAperTaxa <- dcast(TaxaData, Taxon_ID~., length, value.var="ASPA_No") #Cast to find the number of ASPAs each taxa occurs in
NumTaxainOneASPA <- nrow(subset(NumASPAperTaxa, .==1))/nrow(NumASPAperTaxa) #Find number of taxa only occuring in one ASPA and divide by total number of taxa to get percentage

#### Stats for Fig 1a and manuscript ####
##1a Protection statistics by ACBR
ACBRPercentageProt

##Manuscript 

#Percentage of species protected in at least one biodiversity ASPA
PercBioProtTaxa
#Percent of protected species only occurring in nonbiodiversity designated ASPAs
PercentNonBiodivSpecies
#Percent of protected species only occurring in one ASPA
NumTaxainOneASPA

##Overall number of species occurring in protected areas, total and by taxonomic group
ByTaxaPercentageProt <- rbindlist(lapply(c("All", "Chordates", "PlantLichen", "Inverts"), function (x){ #List through the 4 categories (all species, Chordates, PlantLichen and Invertebrates) and return a dataframe of protection stats
  if(x=="Chordates"){ #Subset to the appropriate group (or use the whole dataset in the cast of 'All')
    TaxaData <- subset(AntarcticData, PHYLUM=="Chordata")
  } else if(x=="PlantLichen"){
    TaxaData <- subset(AntarcticData, KINGDOM=="Fungi" | KINGDOM=="Plantae")
  } else if(x=="Inverts"){
    TaxaData <- subset(AntarcticData, KINGDOM=="Animalia" & PHYLUM!="Chordata")
  } else {
    TaxaData <- AntarcticData
  }
  
  Taxa <- unique(TaxaData[,c("Taxon_ID", "BinaryProt")]) #For each taxa, get it's binary protection status (this reduces to a long form datatable, but many taxa have some locations within ASPAs and some without, so these will have two entries, one with binaryprot=1 and one where it =0. We must tease these out)
  NumTaxa <- length(unique(Taxa$Taxon_ID)) #Get the total number of species (by finding the unique number of taxa)
  
  ProtTaxa <- dcast(Taxa, Taxon_ID~BinaryProt, value.var="BinaryProt") #Cast the data so that we have the taxa in rows, and a column with showing whether that taxa has some records in ASPAs, (1) and the next for whether the taxa does not (0)
  ProtTaxa[is.na(ProtTaxa)] <- 0 #Change NAs to 0s
  ProtTaxa <- nrow(ProtTaxa[ProtTaxa[,3]==1,]) #Subset the data to only taxa that have a 1 in the 1 column (indicates at least some locations protected) and find the number of rows to get the number of taxa
  
  NumProtTaxa <- as.data.frame(ProtTaxa) #Change values to dataframes for collation
  PercProtTaxa <- as.data.frame(ProtTaxa/NumTaxa) #the percentage of protected taxa is number of protected taxa/total number of taxa
  NumTaxa <- as.data.frame(NumTaxa)
  Summary <- cbind(NumTaxa, NumProtTaxa, PercProtTaxa)
  Summary$Group <- x
  return(Summary)
}))

#And now get a statistic of number of Antarctic species occuring in at least one *BIODIVERSITY* primary designated ASPA
Taxa <- unique(AntarcticData[,c("Taxon_ID", "BinaryProt", "Biodiversity_designated")]) #For each taxa, get it's binary protection status (this reduces to a long form datatable, but many taxa have some locations within ASPAs and some without, so these will have two entries, one with binaryprot=1 and one where it =0. We must tease these out)
NumTaxa <- length(unique(Taxa$Taxon_ID)) #Get the total number of species (by finding the unique number of taxa)

BioProtTaxa <- dcast(Taxa, Taxon_ID~Biodiversity_designated, value.var="BinaryProt") #Cast the data so that we have the taxa in rows, and a column with showing whether that taxa has some records in ASPAs, (1) and the next for whether the taxa does not (0)
BioProtTaxa[is.na(BioProtTaxa)] <- 0 #Change NAs to 0s
BioProtTaxa <- nrow(BioProtTaxa[BioProtTaxa[,3]==1,]) #Subset the data to only taxa that have a 1 in the 1 column (indicates at least some locations protected) and find the number of rows to get the number of taxa

NumBioProtTaxa <- as.data.frame(BioProtTaxa) #Change values to dataframes for collation
PercBioProtTaxa <- as.data.frame(BioProtTaxa/NumTaxa) #the percentage of protected taxa is number of protected taxa/total number of taxa

print(ByTaxaPercentageProt)
print(PercBioProtTaxa)

#### Supp Figure 1, ACBR Stats ####

###Total number of species and percentage protected, split by species in biodiversity and non biodiversity ASPAs
ACBRPercentageBioProt <- rbindlist(lapply(c(1:16), function(ACBR){ #List through the 16 ACBRs and return a dataframe of protection stats
  ACBRData <- subset(AntarcticData, ACBR_ID==ACBR) #subset to ACBR
  ACBRData <- unique(ACBRData[,c("Taxon_ID", "BinaryProt", "Biodiversity_designated")]) ##For each taxa, get it's binary protection status and biodiversity designation status (this reduces to a long form datatable, but many taxa have some locations within ASPAs and some without, and some binary designated and some not. We must tease these out)
  ACBRData[is.na(ACBRData)] <- 0 
  NumTaxa <- length(unique(ACBRData$Taxon_ID)) #Get the total number of species (by finding the unique number of taxa)
  
  ProtTaxa <- dcast(ACBRData, Taxon_ID~BinaryProt, length, value.var="BinaryProt") #Cast the data so that we have the taxa in rows, and a column with showing whether that taxa has some records in ASPAs, (1) and the next for whether the taxa does not (0)
  
  if(names(ProtTaxa)[2]==0 & ncol(ProtTaxa)==2){ #If there's only two columns and the cast column is '0' this means no species have protection
    NumNonBioProtTaxa <- 0
    NumBioProtTaxa <- 0
  } else {
    names(ProtTaxa) <- c("Taxon_ID", "NotProt", "Prot") #If there's 3 columns, rename them
    ProtTaxaBiodiv <- dcast(ACBRData, Taxon_ID~Biodiversity_designated, length, value.var="Biodiversity_designated") #Cast again to see if biodiversity designated or not
    if(ncol(ProtTaxaBiodiv)==2){ #If there's only two columns this means either all taxa are biodiversity protected, or none. The 'ifelse's in the next two lines tease this out
      NumBioProtTaxa <- ifelse(names(ProtTaxaBiodiv)[2]==0,0,nrow(subset(ProtTaxa, Prot>0)))
      NumNonBioProtTaxa <- ifelse(names(ProtTaxaBiodiv)[2]==0,nrow(subset(ProtTaxa, Prot>0)), 0)
    } else {
      names(ProtTaxaBiodiv) <- c("Taxon_ID", "NotBiodivProt", "BiodivProt") #If there's 3 columns some are biodiversity protected and some not
      ProtTaxa <- merge(ProtTaxa, ProtTaxaBiodiv, by="Taxon_ID") #Add biodiv prot data to binary prot data
      ProtTaxa[is.na(ProtTaxa)] <- 0 
      NumBioProtTaxa <- nrow(subset(ProtTaxa, Prot>0 & BiodivProt>0)) #Num bio prot is number of protected taxa that also have some biodiversity protection
      NumNonBioProtTaxa <- nrow(subset(ProtTaxa, Prot>0 & BiodivProt==0)) #Num non bio prot is number of protected taxa that don't have have some biodiversity protection. 
    }
  }

  PercBioProt <- as.data.frame(NumBioProtTaxa/NumTaxa*100) #Calculate percentages and convert to dataframe for compiling
  PercNonBioProt <- as.data.frame(NumNonBioProtTaxa/NumTaxa*100)
  NumTaxa <- as.data.frame(NumTaxa)
  NumProtTaxa <- as.data.frame(NumBioProtTaxa+NumNonBioProtTaxa)
  
  Summary <- cbind(NumTaxa, NumProtTaxa, PercBioProt, PercNonBioProt)
  names(Summary) <- c("NumTaxa", "NumProtTaxa", "PercBioProt", "PercNonBioProt")
  Summary$ACBR_ID <- ACBR
  return(Summary)
}))

###Area of each ACBR protected
ACBRASPA <- gIntersection(ACBRPoly, ASPAPoly, byid=TRUE) #Intersect ASPA and ACBR to create a file with both

ACBRASPAArea <- as.data.frame(gArea(ACBRASPA, byid=TRUE))
names(ACBRASPAArea) <- c("Intersect_Area") #Rename
ACBRASPAArea$ASPAPoly <- sapply(1:nrow(ACBRASPAArea), function (x) str_split(rownames(ACBRASPAArea)[[x]], " ")[[1]][2]) #Get the ASPA polygon number (below we convert this to the correct ASPA number)
ACBRASPAArea$ACBRPoly <- sapply(1:nrow(ACBRASPAArea), function (x) str_split(rownames(ACBRASPAArea)[[x]], " ")[[1]][1]) #Get the ACBR polygon number (below we convert this to the correct ABCR number)

ACBRPolydf <- as.data.frame(ACBRPoly) #Find what the actual ACBR number of each ACBR polygon is
ACBRPolydf$ACBRPoly <- rownames(ACBRPolydf) #Add polygon number in (from rownames)

ASPAPolydf <- as.data.frame(ASPAPoly) #Find what the actual ASPA number of each ASPA polygon is
ASPAPolydf$ASPAPoly <- rownames(ASPAPolydf) #Add polygon number in (from rownames)

#Merge all the dataframes together, finished file is every intersected area of ACBR and ASPA
ACBRASPAArea <- merge(ACBRASPAArea, ACBRPolydf, by="ACBRPoly") 
ACBRASPAArea <- merge(ACBRASPAArea, ASPAPolydf, by="ASPAPoly")
ACBRASPAArea <- merge(ACBRASPAArea, Desig[,c(1:3)], by="ASPA_No") #Add in designation details for each ASPA

#Amount of area protected in each ACBR by designation criteria
ACBRProtArea <- dcast(ACBRASPAArea, ACBR_ID~Protocol_designation, sum, value.var="Intersect_Area")

#There are 3 ASPAs that don't intersect with the ACBR polygon but do fall in the ACBRs. Add them in:
#107 - Emperor Islands, amongst ACBR 3
#162 - Mawsons Hut, amongst ACBR 13
#166 - Port Martin, amongst ACBR 13 
DesigSub <- subset(Desig, ASPA_No==107 | ASPA_No==162 | ASPA_No==166)
for(i in 1:nrow(DesigSub)){
  ACBRSub <- DesigSub$Desig_ACBR_ID[i]
  ASPADesig <- DesigSub$Protocol_designation[i]
  ASPAArea <- DesigSub$AREA[i]*1000000
  ACBRProtArea[ACBRProtArea$ACBR==ACBRSub,paste(ASPADesig)] <- ACBRProtArea[ACBRProtArea$ACBR==ACBRSub,ASPADesig] + ASPAArea
}

#Find the area of each ACBR polygon in the shapefile
ACBRArea <- as.data.frame(gArea(ACBRPoly, byid=TRUE)) #Area of each ACBR polygon
names(ACBRArea) <- "Area"
ACBRArea$ACBRPoly <- rownames(ACBRArea) 
ACBRPolydf <- as.data.frame(ACBRPoly) #Get the actual ACBR names (As above)
ACBRPolydf$ACBRPoly <- rownames(ACBRPolydf) #Get the actual ACBR names (As above)
ACBRArea <- merge(ACBRArea, ACBRPolydf, by="ACBRPoly") #Get the actual ACBR names (As above)

#Then cast for area of each ACBR
ACBRAreaCast <- dcast(ACBRArea, ACBR_ID~., sum, value.var="Area") #Get total area of each ACBR
ACBRAreaCast$Area_Km <- ACBRAreaCast$./1000000 #Convert to km squared

#Now combine area of ACBRs with protected area of ACBRs to find percentage of each protected by designation
ACBRAreaCast2 <- ACBRAreaCast[ACBRAreaCast$ACBR_ID %in% ACBRProtArea$ACBR_ID,] #Subset to only ACBRs that have some form of protection
ACBRAreaProp <- as.data.frame(cbind(ACBRProtArea[,1], apply(ACBRProtArea[,2:9], 2, function(x) x/ACBRAreaCast2$.))) #Find proportion of area in each ACBR protected by each ASPA desgination
ACBRAreaProp$PercProtArea <- apply(ACBRAreaProp[,2:9], 1, sum)*100 #Total protected across desginations
ACBRAreaProp$PercBioProtArea <- (ACBRAreaProp$A + ACBRAreaProp$B + ACBRAreaProp$C + ACBRAreaProp$E)*100 #Designation D not included here because no D ASPAs
ACBRAreaProp$PercNonBioProtArea <- ACBRAreaProp$PercProt - ACBRAreaProp$PercBioProt
ACBRAreaProp <- ACBRAreaProp[,c(1,11:12)]
names(ACBRAreaProp)[1] <- "ACBR_ID"

###Percentage of each ACBR sampled
#These first few lines create a blank raster of the same extent as the ACBR shapefile in 1km grid cells, and then assigns each of the ACBRs ids to any raster cells overlapping the ACBR polygons
ACBRRas <- raster(ext=extent(ACBRPoly), resolution=1000, crs=CRS("+proj=stere +lat_0=-90 +lat_ts=-71 +lon_0=0 +k=1 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0"))
ACBRRas2 <- rasterize(ACBRPoly, ACBRRas, "ACBR_ID")
ACBRAreaRaster <- sapply(1:16, function (x) length(ACBRRas2[ACBRRas2==x])) #Get the total number of pixels in each ACBR

#Now find the number of surveyed pixels
ACBRUnique <- ACBRRas2 #Make a new raster of same size
values(ACBRUnique) <- 1:length(ACBRRas2) #Change the values so each cell has a unique value
DataPoints <- cbind(AntarcticPoints$Longitude, AntarcticPoints$Latitude)
DataPoints <- SpatialPointsDataFrame(DataPoints, AntarcticPoints, proj4string = CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"))
DataPoints <- spTransform(DataPoints, CRS("+proj=stere +lat_0=-90 +lat_ts=-71 +lon_0=0 +k=1 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0"))

ACBR_extract <- raster::extract(ACBRRas2, DataPoints) #This finds the ACBR each point lies in, by raster pixel
Pixel_extract <- raster::extract(ACBRUnique, DataPoints) #And this gives each occurrence point the unique pixel value it falls in
ACBRvsSurveyedPixels <- as.data.frame(cbind(ACBR_extract, Pixel_extract))
ACBRvsSurveyedPixels <- unique(ACBRvsSurveyedPixels) #This gives us the number of surveyed pixels in each ACBR (unique so we don't double count multiple counts in one pixel)
ACBRvsSurveyedPixels <- dcast(ACBRvsSurveyedPixels, ACBR_extract~., length, value.var="Pixel_extract") #Cast to get number of pixels in each ACBR
ACBRvsSurveyedPixels <- ACBRvsSurveyedPixels[!is.na(ACBRvsSurveyedPixels$ACBR_extract),] #Remove the NAs (we don't care about them)
ACBRvsSurveyedPixels <- cbind(ACBRvsSurveyedPixels, ACBRAreaRaster) #Add total pixels in each ACBR to the dataframe
ACBRvsSurveyedPixels$PercSampled <- (ACBRvsSurveyedPixels$./ACBRvsSurveyedPixels$ACBRAreaRaster)*100 #find out percentage sampled pixels/total pixels
names(ACBRvsSurveyedPixels) <- c("ACBR_ID", "NumPixelsSurveyed", "NumACBRPixels", "PercSampled")
ACBRvsSurveyedPixels <- ACBRvsSurveyedPixels[,c("ACBR_ID", "PercSampled")]

### Bring all the data together and plot
ACBRStats <- merge(ACBRPercentageBioProt, ACBRAreaProp, by="ACBR_ID", all=T)
ACBRStats <- merge(ACBRStats, ACBRvsSurveyedPixels, by="ACBR_ID", all=T)
ACBRStats[is.na(ACBRStats)] <- 0

ACBR_NumSpecies_Plot <- ggplot(ACBRStats, aes(y=NumTaxa, x=ACBR_ID)) +  #Plot number of species occurring in each ACBR
  geom_bar(stat="identity", fill="#9DC3E6")+
  xlab('ACBR ID')+
  ylab('Total Number of Species')+
  scale_x_continuous(expand = c(0,0), breaks=c(1:16))+
  scale_y_continuous(expand = c(0,0), breaks=seq(0,800,100), limits=c(0,800))+
  theme(panel.background = element_rect(fill = BackgroundColor), plot.background = element_rect(fill = BackgroundColor),
        panel.grid = element_blank(), axis.ticks.y = element_blank(), axis.line = element_line(color="#2e5f8cff"),
        axis.ticks.x = element_blank(), plot.margin =unit(c(5,5,5,5),"mm"), legend.spacing = unit(c(0,0,0,0),"mm"),
        text = element_text(size=13, family="Helvetica Neue"), legend.position="none", axis.title.x=element_text(colour="#2e5f8cff"),
        axis.title.y=element_text(colour="#2e5f8cff"), axis.text.x=element_text(colour="#2e5f8cff"), axis.text.y=element_text(colour="#2e5f8cff"))

tiff(paste0(OutputFP, 'Sup1a_ACBRNumSpecies.tiff'), width = 2000, height = 2000, units = "px", res=500)
ACBR_NumSpecies_Plot
dev.off()

ACBRStatsBio <- melt(ACBRStats[,c("ACBR_ID", "PercBioProt", "PercNonBioProt")], id.vars="ACBR_ID") #Melt so that GGPlot can make split bar graphs

ACBR_PercProt_Plot <- ggplot(ACBRStatsBio, aes(fill=variable, y=value, x=ACBR_ID)) + 
  geom_bar(position="stack", stat="identity")+
  xlab('ACBR ID')+
  ylab('Percentage Species Protected')+
  scale_fill_manual(values=c("#478b33ff","#75044fff"))+
  scale_x_continuous(expand = c(0,0), breaks=c(1:16))+
  scale_y_continuous(expand = c(0,0), breaks=seq(0,100,10), limits=c(0,100))+
  theme(panel.background = element_rect(fill = BackgroundColor), plot.background = element_rect(fill = BackgroundColor),
        panel.grid = element_blank(), axis.ticks.y = element_blank(), axis.line = element_line(color="#2e5f8cff"),
        axis.ticks.x = element_blank(), plot.margin =unit(c(5,5,5,5),"mm"), legend.spacing = unit(c(0,0,0,0),"mm"),
        text = element_text(size=13, family="Helvetica Neue"), legend.position="none", axis.title.x=element_text(colour="#2e5f8cff"),
        axis.title.y=element_text(colour="#2e5f8cff"), axis.text.x=element_text(colour="#2e5f8cff"), axis.text.y=element_text(colour="#2e5f8cff"))

tiff(paste0(OutputFP, 'Sup1b_ACBRProtSpec.tiff'), width = 2000, height = 2000, units = "px", res=500)
ACBR_PercProt_Plot
dev.off()

ACBRStatsBioArea <- melt(ACBRStats[,c("ACBR_ID", "PercBioProtArea", "PercNonBioProtArea")], id.vars="ACBR_ID") #Melt so that GGPlot can make split bar graphs

ACBR_Area_Plot <- ggplot(ACBRStatsBioArea, aes(fill=variable, y=value, x=ACBR_ID)) + 
  geom_bar(position="stack", stat="identity")+
  xlab('ACBR ID')+
  ylab('Percentage Area Protected')+
  scale_fill_manual(values=c("#478b33ff","#75044fff"))+
  scale_x_continuous(expand = c(0,0), breaks=c(1:16))+
  scale_y_continuous(expand = c(0,0), breaks=c(0:5), limits=c(0,5))+
  theme(panel.background = element_rect(fill = BackgroundColor), plot.background = element_rect(fill = BackgroundColor),
        panel.grid = element_blank(), axis.ticks.y = element_blank(), axis.line = element_line(color="#2e5f8cff"),
        axis.ticks.x = element_blank(), plot.margin =unit(c(5,5,5,5),"mm"), legend.spacing = unit(c(0,0,0,0),"mm"),
        text = element_text(size=13, family="Helvetica Neue"), legend.position="none", axis.title.x=element_text(colour="#2e5f8cff"),
        axis.title.y=element_text(colour="#2e5f8cff"), axis.text.x=element_text(colour="#2e5f8cff"), axis.text.y=element_text(colour="#2e5f8cff"))

tiff(paste0(OutputFP, 'Sup1c_ACBRProtArea.tiff'), width = 2000, height = 2000, units = "px", res=500)
ACBR_Area_Plot
dev.off()

ACBR_Sampled_Plot <- ggplot(ACBRStats, aes(y=PercSampled, x=ACBR_ID)) + 
  geom_bar(stat="identity", fill="#9DC3E6")+
  xlab('ACBR ID')+
  ylab('Percentage Area Sampled')+
  scale_x_continuous(expand = c(0,0), breaks=c(1:16))+
  scale_y_continuous(expand = c(0,0), breaks=seq(0,30,5), limits=c(0,30))+
  theme(panel.background = element_rect(fill = BackgroundColor), plot.background = element_rect(fill = BackgroundColor),
        panel.grid = element_blank(), axis.ticks.y = element_blank(), axis.line = element_line(color="#2e5f8cff"),
        axis.ticks.x = element_blank(), plot.margin =unit(c(5,5,5,5),"mm"), legend.spacing = unit(c(0,0,0,0),"mm"),
        text = element_text(size=13, family="Helvetica Neue"), legend.position="none", axis.title.x=element_text(colour="#2e5f8cff"),
        axis.title.y=element_text(colour="#2e5f8cff"), axis.text.x=element_text(colour="#2e5f8cff"), axis.text.y=element_text(colour="#2e5f8cff"))

tiff(paste0(OutputFP, 'Sup1d_ACBRSampledArea.tiff'), width = 2000, height = 2000, units = "px", res=500)
ACBR_Sampled_Plot
dev.off()

#### Supp Figure 2, Species Richness and Protected Species per km2 ####
AntRas <- raster(ext=extent(AntPoly), resolution=65000, crs=CRS("+proj=stere +lat_0=-90 +lat_ts=-71 +lon_0=0 +k=1 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0")) #Create a blank raster of the same extent as the Antarctic polygon and 65km grid cells
AntRas2 <- rasterize(AntPoly, AntRas, "SURFACE") #Convert Ant poly into a raster of those dimensions

AntRasUnique <- AntRas2 #Make a new raster of same size and resolution
values(AntRasUnique) <- 1:length(AntRas2) #Change the values so each cell has a unique value

AntPoints <- as.data.frame(rasterToPoints(AntRas2)) #Get a point for the centre of each raster gridcell
DataPointsAnt <- cbind(AntPoints$x, AntPoints$y) #Convert raster points into a Spatial Points Data Frame
DataPointsAnt <- SpatialPointsDataFrame(DataPointsAnt, AntPoints, proj4string = CRS("+proj=stere +lat_0=-90 +lat_ts=-71 +lon_0=0 +k=1 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0"))

AntPoints$RastID <- raster::extract(AntRasUnique, DataPointsAnt) #And give each point the unique pixel value it falls in

RichnessPoints[,c("Lon_WGS", "Lat_WGS")] <- NULL #Remove WGS coordinates from richness file
names(RichnessPoints) <- c("x", "y", "Richness") #Rename
DataPointsSpec <- cbind(RichnessPoints$x, RichnessPoints$y) #Convert species occuring points into a Spatial Points Data Frame
DataPointsSpec <- SpatialPointsDataFrame(DataPointsSpec, RichnessPoints, proj4string = CRS("+proj=stere +lat_0=-90 +lat_ts=-71 +lon_0=0 +k=1 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0"))

AntVGM <- variogram(Richness~1, DataPointsSpec) #Fit a variogram to richness in each gridcell (for kriging)
AntFit <- fit.variogram(AntVGM, model=vgm(1, "Lin", 0)) # fit model

AntKrige <- as.data.frame(krige(Richness~1, DataPointsSpec, DataPointsAnt, AntFit)) #Obtain kriged values for all Antarctic points

RichnessMap <- ggplot(AntKrige, aes(x=coords.x1, y=coords.x2)) + #Plot kriged richness map. This will say "regions define for each polygons". This is fine. 
  geom_tile(aes(fill=var1.pred)) + coord_equal() +
  geom_polygon(data = AntPoly, aes(x=long, y = lat, group = group), fill = NA, color = "#2e5f8cff", size=0.1)+
  scale_fill_gradient(low = BackgroundColor, high="#1c3955ff", breaks=c(0, 250, 500)) +
  guides(fill=guide_colorbar(ticks = FALSE,title=NULL))+
  theme(panel.background = element_rect(fill = BackgroundColor), plot.background = element_rect(fill = BackgroundColor),
        panel.grid = element_blank(), axis.ticks.y = element_blank(),
        axis.ticks.x = element_blank(), plot.margin =unit(c(5,5,5,5),"mm"), legend.spacing = unit(c(0,0,0,0),"mm"),
        text = element_text(size=12, family="Helvetica Neue"),legend.text = element_text(colour="#2e5f8cff"), legend.direction = "horizontal",
        legend.position=c(0.3,0.1), axis.title.x=element_blank(),
        axis.title.y=element_blank(), axis.text.x=element_blank(), axis.text.y=element_blank())

tiff(paste0(OutputFP, 'Sup2a_RichnessMap.tiff'), width = 2000, height = 2000, units = "px", res=500)
RichnessMap
dev.off()

### Find the proportion of species protected per km squared in each ACBR
ACBRProtArea$AreaKM <- rowSums(ACBRProtArea[, c(2:ncol(ACBRProtArea))])/1000000 #ACBRProtArea taken from section above, calculate overall area protected in each ACBR (and divide to get km2)
ACBRStats <- merge(ACBRStats, ACBRProtArea[,c(1,10)], by="ACBR_ID", all=T) #ACBRStats taken from section above
ACBRStats$ProtbyKM <- ACBRStats$NumProtTaxa/ACBRStats$AreaKM #Get number of taxa protected per km2
ACBRStats[is.na(ACBRStats$AreaKM),]$ProtbyKM <- 0 #Change NAs to zeros
ACBRStats[is.na(ACBRStats$AreaKM),]$AreaKM <- 0

#Now plot
ACBRCols <- c("#750404ff", "#ff7f7fff", "#e60000ff", "#ffff00ff", "#ffaa00ff", "#abcd68ff", "#63e228ff",
              "#478b33ff", "#06c6ffff", "#0d8aadff", "#cdcdceff", "#6a6a6aff", "#75044fff", "#78e0ffff", 
              "#ff75e0ff", "#045fe6ff") #These colours correspond to the standard ACBR colours

SpecByArea <- ggplot(ACBRStats, aes(fill=as.factor(ACBR_ID), y=sqrt(ProtbyKM), x=ACBR_ID)) + #Plot square root of number of species protected per km2 of ASPA for each ACBR
  coord_flip()+
  geom_bar(position="stack", stat="identity")+
  xlab('ACBR ID')+
  ylab(expression(sqrt(paste("No. species per km"^{2}," of ASPA"))))+
  scale_fill_manual(values=ACBRCols)+
  scale_y_continuous(expand = c(0,0), breaks=c(seq(0,10,2)) ,position = "right")+
  scale_x_reverse(expand = c(0,0), breaks=c(1:16))+
  theme(panel.background = element_rect(fill = BackgroundColor), plot.background = element_rect(fill = BackgroundColor),
        panel.grid = element_blank(), axis.ticks.y = element_blank(),
        axis.line = element_line(color="#2e5f8cff"),
        axis.ticks.x = element_blank(), plot.margin =unit(c(5,5,5,5),"mm"), legend.spacing = unit(c(0,0,0,0),"mm"),
        text = element_text(size=13, family="Helvetica Neue"), legend.position="none", axis.title.x=element_text(colour="#2e5f8cff", margin = margin(t=0, r=0, b=0, l=50)),
        axis.title.y=element_text(colour="#2e5f8cff"), axis.text.x=element_text(colour="#2e5f8cff"), axis.text.y=element_text(colour="#2e5f8cff"))

tiff(paste0(OutputFP, 'Sup2b_SpecByArea.tiff'), width = 2000, height = 2000, units = "px", res=500)
SpecByArea
dev.off()


#### Supp Figure 3, Top ten protected species by Area ####

TopTens <- rbindlist(lapply(c("Chordates", "PlantLichen", "Inverts"), function (x){
  if(x=="Chordates"){
    TaxaData <- unique(subset(AntarcticData, PHYLUM=="Chordata" & BinaryProt==1)[,c("Taxon_ID", "ASPA_No")]) #Take chordates that are protected and the unique ones in each ASPA
  } else if(x=="PlantLichen"){
    TaxaData <- unique(subset(AntarcticData, KINGDOM=="Fungi" | KINGDOM=="Plantae" & BinaryProt==1)[,c("Taxon_ID", "ASPA_No")]) #As above for PlantLichen
  } else {
    TaxaData <- unique(subset(AntarcticData, KINGDOM=="Animalia" & PHYLUM!="Chordata" & BinaryProt==1)[,c("Taxon_ID", "ASPA_No")]) #As above for invertebrates
  }
  TaxaData <- merge(TaxaData, Desig, by=c("ASPA_No")) #Get area for each ASPA from desig
  TaxaData$AREA <- as.numeric(as.character(TaxaData$AREA))
  ASPAArea <- dcast(TaxaData, Taxon_ID~., sum, value.var="AREA") #Find total area protected for each taxa
  names(ASPAArea) <- c("Taxon_ID", "ASPAArea")
  ASPAArea <- merge(ASPAArea, TaxonInfo, by="Taxon_ID") #Add full taxon info
  ASPAArea <- head(ASPAArea[order(ASPAArea$ASPAArea, decreasing=TRUE),],10) #Take top ten most protected
  ASPAArea$Group <- x
  return(ASPAArea)
}))

TopTens <- merge(TopTens, ChordateCommonNames, by="Taxon_ID", all=TRUE) #Add chordate common names
TopTens <- TopTens[!is.na(TopTens$ASPAArea),] #Remove NAs (Removes chordates common names we haven't used)
TopTens$Name <- ifelse(is.na(TopTens$CommonName), paste(TopTens$GENUS, TopTens$SPECIES, sep=" "), paste(TopTens$CommonName)) #Create a name column

TopNumGraph <- max(TopTens$ASPAArea) #Get max area to standardise graphs

TaxaGraphArea <- function(TaxGroup){
  GraphTheTaxa <- subset(TopTens, Group==TaxGroup)
  if(TaxGroup=="Chordates"){
    xaxis <- element_text(colour="#2e5f8cff", hjust=1, size=11, family="Helvetica Neue")
  } else {
    xaxis <- element_text(colour="#2e5f8cff", hjust=1, size=11, family="Helvetica Neue", face="italic") #Make taxa names italic for scientific names
  }
  GraphTheTaxa <- GraphTheTaxa[order(GraphTheTaxa$ASPAArea)] #Order so the most protected species are listed first
  GraphTheTaxa$Name <- factor(GraphTheTaxa$Name, levels = GraphTheTaxa$Name)
  
  protocol_cols <- c("A" = "#ffab04","B" = "#478b33","C" = "#65912b", "E" = "#acce6a","F" = "#ff6c04","G" = "#e63404","H" = "#ffdc03", "I" = "#754204")
  
  ggplot(GraphTheTaxa, aes(x=Name, y=ASPAArea))+ #Create the plot of ten most protected taxa
    geom_bar(fill="#9DC3E6", stat="identity")+
    coord_flip()+
    xlab("Species")+
    ylab("Number of ASPAs")+
    scale_y_continuous(expand = c(0, 0), breaks=pretty_breaks(), limits = c(0, TopNumGraph))+
    theme(panel.background = element_rect(fill = BackgroundColor), plot.background = element_rect(fill = BackgroundColor),
          panel.grid = element_blank(), axis.ticks.y = element_blank(), axis.line = element_line(color="#2e5f8cff"),
          axis.ticks.x = element_blank(), plot.margin =unit(c(5,5,5,5),"mm"), legend.spacing = unit(c(0,0,0,0),"mm"),
          axis.title.x=element_blank(), 
          axis.title.y=element_blank(), 
          axis.text.x=element_text(colour="#2e5f8cff", size=11, family="Helvetica Neue"), 
          axis.text.y=xaxis,
          legend.position="none")
}

tiff(paste0(OutputFP, 'Sup3a_ChordateGraphArea.tiff'), width = 2300, height = 2000, units = "px", res=500)
TaxaGraphArea("Chordates")
dev.off()

tiff(paste0(OutputFP, 'Sup3b_PlantLichenGraphArea.tiff'), width = 2300, height = 2000, units = "px", res=500)
TaxaGraphArea("PlantLichen")
dev.off()

tiff(paste0(OutputFP, 'Sup3c_InvertGraphArea.tiff'), width = 2300, height = 2000, units = "px", res=500)
TaxaGraphArea("Inverts")
dev.off()



#### Supp Figure 4, Designation Stats ####
#Find number of species in each ASPA of each protocol designation, get median
Protocol_designation <- c("A", "B", "C", "D", "E", "F", "G", "H", "I")
Description <- c("Inviolate", "Ecosystem", "Species", "Type Locality", "Scientific", "Geological", "Aesthetic", "Historical", "General")
DesigNames <- as.data.frame(cbind(Protocol_designation, Description))
names(DesigNames) <- c("Protocol_designation", "Description")
DesigNames$Description <- factor(DesigNames$Description, levels=DesigNames$Description)
Colours <- c("#478b33ff","#478b33ff","#478b33ff","#478b33ff","#75044fff","#75044fff","#478b33ff","#75044fff","#75044fff")

ASPATaxa <- unique(subset(AntarcticData, BinaryProt==1)[,c("Taxon_ID", "ASPA_No", "Protocol_designation")]) #Get the unique taxa in each ASPA (+protcol designation of that ASPA)

NumTaxaPerASPA <- dcast(ASPATaxa, ASPA_No + Protocol_designation ~.,length, value.var="Taxon_ID") #Cast to find number of taxa in each ASPA
names(NumTaxaPerASPA) <- c("ASPA_No", "Protocol_designation", "NumTaxa") #Add names

#Median plot

MedianTaxaPerDesig <- dcast(NumTaxaPerASPA, Protocol_designation ~., median, fill=0, value.var="NumTaxa") #Find median number of taxa in ASPAs of each protocol designation
names(MedianTaxaPerDesig) <- c("Protocol_designation", "Median")

#And now plot
MedianTaxaPerDesig <- merge(MedianTaxaPerDesig, DesigNames, by="Protocol_designation", all=TRUE) #Add descriptions of each protocol designation
MedianTaxaPerDesig$Protocol_designation <- as.character(MedianTaxaPerDesig$Protocol_designation)
MedianTaxaPerDesig <- MedianTaxaPerDesig[order(MedianTaxaPerDesig$Protocol_designation),] #Order from designations A-H
MedianTaxaPerDesig$Description <- factor(MedianTaxaPerDesig$Description, levels = MedianTaxaPerDesig$Description) #Make the description a factor so it's ordered correctly in plot
MedianTaxaPerDesig[is.na(MedianTaxaPerDesig)] <- 0

Yaxis_UpperLim <- (max(MedianTaxaPerDesig$Median))+10 #To set the y axis large enough
MedianDesigPlot <- ggplot(data=MedianTaxaPerDesig,aes(x=Description, y=Median, fill=Protocol_designation))+ #Plots mean number of species at each designation
  geom_bar(stat="identity")+
  coord_flip()+
  scale_fill_manual(values=Colours)+
  scale_y_continuous(expand = c(0,0), limits=c(0,Yaxis_UpperLim))+ 
  scale_x_discrete(expand = c(0,0))+
  ylab("Median number of species")+
  theme(panel.background = element_rect(fill = BackgroundColor), plot.background = element_rect(fill = BackgroundColor),
        panel.grid = element_blank(), axis.ticks.y = element_blank(), axis.line = element_line(color="#2e5f8cff"),
        axis.ticks.x = element_blank(), plot.margin =unit(c(5,5,5,5),"mm"), legend.spacing = unit(c(0,0,0,0),"mm"),
        text = element_text(size=10, family="Helvetica Neue"), legend.position="none", axis.title.x=element_text(colour="#2e5f8cff", margin=margin(10,0,0,0)), 
        axis.title.y=element_blank(), axis.text.x=element_text(colour="#2e5f8cff", size=10, family="Helvetica Neue"), axis.text.y=element_text(colour="#2e5f8cff", size=10, family="Helvetica Neue"))
tiff(paste0(OutputFP, 'Sup4a_DesigMedian.tiff'), width = 2000, height = 1400, units = "px", res=500)
MedianDesigPlot
dev.off()

#Total taxa plot
ProtSpecPerDesig <- unique(ASPATaxa[c("Taxon_ID","Protocol_designation")]) #For unique sum of taxa in each protocol designation (otherwise taxa x might occur in two ASPAs of protoc. desig. B, in which case we would count x twice)
TotalTaxaPerDesig <- dcast(ProtSpecPerDesig, Protocol_designation~., length, value.var="Taxon_ID") #Cast to get number of Taxa
names(TotalTaxaPerDesig) <- c("Protocol_designation", "Sum") #Add names
TotalTaxaPerDesig <- merge(TotalTaxaPerDesig, DesigNames, by="Protocol_designation", all=TRUE) #Add names for plotting
TotalTaxaPerDesig$Protocol_designation <- as.character(TotalTaxaPerDesig$Protocol_designation)
TotalTaxaPerDesig <- TotalTaxaPerDesig[order(TotalTaxaPerDesig$Protocol_designation),] #order
TotalTaxaPerDesig$Description <- factor(TotalTaxaPerDesig$Description, levels = TotalTaxaPerDesig$Description) #change names to factor
TotalTaxaPerDesig[is.na(TotalTaxaPerDesig)] <- 0 #change NAs to 0

Yaxis_UpperLim <- (max(TotalTaxaPerDesig$Sum))+10 #To set the y axis large enough
TotalDesigPlot <- ggplot(data=TotalTaxaPerDesig,aes(x=Description, y=Sum, fill=Description))+ #Plots sum number of species at each designation
  geom_bar(stat="identity")+
  coord_flip()+
  scale_fill_manual(values=Colours)+
  scale_y_continuous(expand = c(0,0), limits=c(0,Yaxis_UpperLim))+ 
  scale_x_discrete(expand = c(0,0))+
  ylab("Total number of species")+
  theme(panel.background = element_rect(fill = BackgroundColor), plot.background = element_rect(fill = BackgroundColor),
        panel.grid = element_blank(), axis.ticks.y = element_blank(), axis.line = element_line(color="#2e5f8cff"),
        axis.ticks.x = element_blank(), plot.margin =unit(c(5,5,5,5),"mm"), legend.spacing = unit(c(0,0,0,0),"mm"),
        text = element_text(size=10, family="Helvetica Neue"), legend.position="none", axis.title.x=element_text(colour="#2e5f8cff", margin=margin(10,0,0,0)), 
        axis.title.y=element_blank(), axis.text.x=element_text(colour="#2e5f8cff", size=10, family="Helvetica Neue"), axis.text.y=element_text(colour="#2e5f8cff", size=10, family="Helvetica Neue"))
tiff(paste0(OutputFP, 'Sup4b_DesigTotal.tiff'), width = 2000, height = 1400, units = "px", res=500)
TotalDesigPlot
dev.off()

#Boxplot of number of taxa per ASPA of each designation
NumTaxaPerASPA <- merge(NumTaxaPerASPA, DesigNames, by="Protocol_designation", all=TRUE) #Add desig names
NumTaxaPerASPA$Protocol_designation <- as.character(NumTaxaPerASPA$Protocol_designation) 
NumTaxaPerASPA <- NumTaxaPerASPA[order(NumTaxaPerASPA$Protocol_designation),] #order
NumTaxaPerASPA$Description <- factor(NumTaxaPerASPA$Description, levels = MedianTaxaPerDesig$Description) #Make description a factor so it plots correctly
NumTaxaPerASPA[is.na(NumTaxaPerASPA)] <- 0 #Add NAs

BoxPlotDesig <- ggplot(data=NumTaxaPerASPA,aes(x=Description, y=NumTaxa, color=Description, fill=Description))+ #Plots boxplot of number of species in ASPAs of each designation
  geom_boxplot()+
  coord_flip()+
  scale_fill_manual(values=Colours)+
  scale_colour_manual(values=Colours)+
  ylab("Number of Species")+
  scale_x_discrete(expand = c(0,0))+
  scale_y_continuous(expand = c(0,0))+
  theme(panel.background = element_rect(fill = BackgroundColor), plot.background = element_rect(fill = BackgroundColor),
        panel.grid = element_blank(), axis.ticks.y = element_blank(), axis.line = element_line(color="#2e5f8cff"),
        axis.ticks.x = element_blank(), plot.margin =unit(c(5,5,5,5),"mm"), legend.spacing = unit(c(0,0,0,0),"mm"),
        text = element_text(size=11, family="Helvetica Neue"), legend.position="none", axis.title.x=element_text(colour="#2e5f8cff", margin=margin(10,0,0,0)), 
        axis.title.y=element_blank(), axis.text.x=element_text(colour="#2e5f8cff", size=11, family="Helvetica Neue"), axis.text.y=element_text(colour="#2e5f8cff", size=11, family="Helvetica Neue"))

tiff(paste0(OutputFP, 'Sup4c_DesigBoxPlot.tiff'), width = 2000, height = 1400, units = "px", res=500)
BoxPlotDesig
dev.off()

#Number of ASPAs per designation plot
NumASPAPerDesig <- dcast(Desig, Protocol_designation~., length, value.var="ASPA_No") #Cast ASPA details file to get number of ASPAs per designation
names(NumASPAPerDesig) <- c("Protocol_designation", "NumASPAs") #Name
NumASPAPerDesig <- merge(NumASPAPerDesig, DesigNames, by="Protocol_designation", all=TRUE) #Add Desig details
NumASPAPerDesig$Protocol_designation <- as.character(NumASPAPerDesig$Protocol_designation) 
NumASPAPerDesig <- NumASPAPerDesig[order(NumASPAPerDesig$Protocol_designation),] #Order
NumASPAPerDesig$Description <- factor(NumASPAPerDesig$Description, levels = NumASPAPerDesig$Description) #Make description a factor so it plots correctly
NumASPAPerDesig[is.na(NumASPAPerDesig)] <- 0

Yaxis_UpperLim <- (max(NumASPAPerDesig$NumASPAs))+10 #To set the y axis large enough
NumASPAsDesigPlot <- ggplot(data=NumASPAPerDesig,aes(x=Description, y=NumASPAs, fill=Description))+ #Plots number of ASPAs at each designation
  geom_bar(stat="identity")+
  coord_flip()+
  scale_fill_manual(values=Colours)+
  scale_y_continuous(expand = c(0,0), limits=c(0,Yaxis_UpperLim))+ 
  scale_x_discrete(expand = c(0,0))+
  ylab("Number of ASPAs")+
  theme(panel.background = element_rect(fill = BackgroundColor), plot.background = element_rect(fill = BackgroundColor),
        panel.grid = element_blank(), axis.ticks.y = element_blank(), axis.line = element_line(color="#2e5f8cff"),
        axis.ticks.x = element_blank(), plot.margin =unit(c(5,5,5,5),"mm"), legend.spacing = unit(c(0,0,0,0),"mm"),
        text = element_text(size=10, family="Helvetica Neue"), legend.position="none", axis.title.x=element_text(colour="#2e5f8cff", margin=margin(10,0,0,0)), 
        axis.title.y=element_blank(), axis.text.x=element_text(colour="#2e5f8cff", size=10, family="Helvetica Neue"), axis.text.y=element_text(colour="#2e5f8cff", size=10, family="Helvetica Neue"))
tiff(paste0(OutputFP, 'Sup4d_DesigNumASPAs.tiff'), width = 2000, height = 1400, units = "px", res=500)
NumASPAsDesigPlot
dev.off()
