##### Scatterplots for area
# SET FOLDER CONNECTIONS
library(plyr)
library(ggpubr)
library(grid)
library(gridExtra)
library(lattice)
library(scales)
library(png)
# data prep
{
INPUT <-"C:/bio/Bio_Backup/TIN R Skripte/GIT/cloudforests/data/"
OUTPUT<-"C:/bio/Bio_Backup/TIN R Skripte/GIT/cloudforests/output/"

tc    <- read.csv (paste0(INPUT,"cf_statistics_newid.txt"),header=T,sep="\t")

full  <- read.csv (paste0(INPUT,"vertsferns_by_cfID_speclist_101518_newid.csv"),sep=";")

CFRegCount_per_spec <- ddply(full, .(taxogroup,scientificname,cf_ass,cf_end), summarise, cfIDCount = length(na.omit(cf_id)))
CFRegCountIsOne <- subset(CFRegCount_per_spec, cfIDCount ==1)

CFSingleRegEndemicsInfo <- merge(CFRegCountIsOne, subset(full,select = c("scientificname","cf_id","CFRegionName","CFRegionContinent")),
                                 by = "scientificname", all.x= TRUE, all.y = FALSE)

agg.cfEndemics <- ddply(CFSingleRegEndemicsInfo, .(cf_id, CFRegionName, CFRegionContinent, taxogroup), summarise,
                        EndSR.cf.assoc = sum(cf_ass),
                        EndSR.cf.restr = sum(cf_end))

agg.cfEndemics <- agg.cfEndemics[order(-agg.cfEndemics$EndSR.cf.restr),]

biodiv     <- ddply(full, .(cf_id, CFRegionName, CFRegionContinent, taxogroup), summarise,
                    cf_ass = sum(cf_ass),
                    cf_end = sum(cf_end))



pp    <- read.table(paste0(INPUT,"pp.txt"),header=T)
coordinates(pp)<-~x+y
coords<- coordinates(pp)
pp    <- pp[,1:2]


# biodiv
biodiv<- merge(biodiv,pp,by.x="cf_id",by.y="ID")

tc2<-tc

tcx<-merge(biodiv,tc2,by.y="ID",by.x="cf_id")
tcx[is.na(tcx)]<-0
tcx$tcf_2001<-(as.double(tcx$gam_3_cf_pr_2001..SUM.)+as.double(tcx$gam_3_cf_un_2001..SUM.)+as.double(tcx$glm_bino_3_cf_pr_2001..SUM.)+as.double(tcx$glm_bino_3_cf_un_2001..SUM.)+as.double(tcx$glm_pois_3_cf_pr_2001..SUM.)+as.double(tcx$glm_pois_3_cf_un_2001..SUM.))/3

tcx$tcf_2001<-tcx$tcf_2001/10000
}


cols<-c(alpha("goldenrod1", 0.5), alpha("royalblue4", 0.5), alpha("darkgreen",0.5), alpha("firebrick",0.5))
groups = c("Mammals","Birds","Cyatheaceae","Amphibians")
for (n in 1:4)
{
group=groups[n]
df_g<-tcx[tcx$taxogroup==group,]
df_g<-as.data.frame(cbind(df_g$cf_ass,df_g$tcf_2001,df_g$cf_id))
colnames(df_g)<-c("species_richness","TCF_area","cf_id")
df_g$species_richness<-log(df_g$species_richness)
df_g$TCF_area<-log(df_g$TCF_area)
maxy<-(max(df_g$species_richness))+(max(df_g$species_richness))/4
#if(maxy<=1){maxy=1}
maxyy<-maxy-maxy/50
title1<-""
title2<-""
if(group == "Mammals")
{
  title1<-"associated"
  title2<-"strict"
  img<-readPNG("C:/bio/R_Backup/cloudforests/figures/figures_9042018/shapes/mammals2.png")
  g <- rasterGrob(img, interpolate=TRUE)
  gxmin=1
  gxmax=4
  gymin=4.5
  gymax=6
  
  breaks1 = c(log(1),log(10),log(100),log(1000))
  labels1 = c("1","10","   100","1,000")
}
if(group == "Birds")
{
  img<-readPNG("C:/bio/R_Backup/cloudforests/figures/figures_9042018/shapes/birds.png")
  g <- rasterGrob(img, interpolate=TRUE)
  gxmin=0.1
  gxmax=6
  gymin=5
  gymax=8
  
  breaks1 = c(log(1),log(10),log(100),log(1000))
  labels1 = c("1","10","100","1,000")
}
if(group == "Cyatheaceae")
{
  img<-readPNG("C:/bio/R_Backup/cloudforests/figures/figures_9042018/shapes/treeferns.png")
  g <- rasterGrob(img, interpolate=TRUE)
  gxmin=.1
  gxmax=4.5
  gymin=3.5
  gymax=5
  
  breaks1 = c(log(1),log(10),log(100),log(1000))
  labels1 = c("1","10","   100","1,000")
}
if(group == "Amphibians")
{
  img<-readPNG("C:/bio/R_Backup/cloudforests/figures/figures_9042018/shapes/amphibians.png")
  g <- rasterGrob(img, interpolate=TRUE)
  gxmin=0.5
  gxmax=4
  gymin=6
  gymax=8
  
  breaks1 = c(log(1),log(10),log(100),log(1000))
  labels1 = c("1","10","100","1,000")
}

assign(paste0('ass',n),ggscatter(df_g, x = "TCF_area", y = "species_richness", 
                                color = cols[n], shape = 19, size = 2, # Points color, shape and size
                                repel = TRUE,
                                label = "cf_id",
                                title = title1,
                                add.params = list(color = cols[n], fill = cols[n]), # Customize reg. line
                                conf.int = TRUE, # Add confidence interval
                                xlab = "", ylab = "",ylim=c(0,maxy))
          + font("title", size = 22, color = "black")
          + annotation_custom(g, xmin=gxmin, xmax=gxmax, ymin=gymin, ymax=gymax)
          + scale_x_continuous(breaks = c(log(10),log(100),log(1000),log(10000),log(100000)),
                               labels = c("10","100","1,000","10,000","100,000"))
       + scale_y_continuous(breaks = breaks1,
                            labels = labels1)
)
                
      
ass1

df_g<-tcx[tcx$taxogroup==group,]
df_g<-as.data.frame(cbind(df_g$cf_end,df_g$tcf_2001,df_g$cf_id))
colnames(df_g)<-c("species_richness","TCF_area","cf_id")
df_g$species_richness<-log(df_g$species_richness)
df_g$TCF_area<-log(df_g$TCF_area)
assign(paste0('str',n),ggscatter(df_g, x = "TCF_area", y = "species_richness", 
                                 color = cols[n], shape = 19, size = 2, # Points color, shape and size
                                 repel = TRUE,
                                 label = "cf_id",
                                 title = title2,
                                 add.params = list(color = cols[n], fill = cols[n]), # Customize reg. line
                                 conf.int = TRUE, # Add confidence interval
                                 xlab = "", ylab = "",ylim=c(0,maxy))
       
       + font("title", size = 22, color = "black")
       + scale_x_continuous(breaks = c(log(10),log(100),log(1000),log(10000),log(100000)),
                            labels = c("10","100","1,000","10,000","100,000"))
       + scale_y_continuous(breaks = breaks1,
                            labels = labels1)
       
)
str1
}


gs<-list(ass1,str1,ass2,str2,ass3,str3,ass4,str4)
pdf(paste0(OUTPUT,"Fig_SX_species_area.pdf"),height=16,width=10)
margin = theme(plot.margin = unit(c(0,1.1,0,0), "cm"))
gs = lapply(gs, "+", margin)

grid.arrange(grobs=gs, ncol=2, 
             top=c(""), bottom=textGrob(bquote("TCF area ("~km^2*")"), gp=gpar(fontsize=24)), 
             left=textGrob("species richness", gp=gpar(fontsize=24),rot=90),right=textGrob("", gp=gpar(fontsize=24),rot=90))
dev.off()

