
threat_data<-read.csv(file.choose())#should be cooccur_threats

#quick reordering for plotting

d1<-threat_data[,-12]
colnames(d1)[12]<-"sp1_name"

long_dat<- rbind(d1,threat_data[,-13])
long_dat$diff <- long_dat$obs_cooccur-long_dat$exp_cooccur

#empty dataframe
coo_threat <- data.frame(matrix(nrow = length(unique(long_dat$threatlevel)), ncol = 4)) 

colnames(coo_threat) = c("threat_status","mean","low_cl","up_cl") 


#look that calculates mean differences and 95 %cl. The mean includes an inverse weight of the commonness of a threat (differences between obs vs exp will be constrained for smaller values)

for( i in 1:length(unique(long_dat$threatlevel))){
  coo_threat[i,1] <- unique(long_dat$threatlevel)[i]
  m<-lm(diff~1,weights = 1/(1+obs_cooccur),data=long_dat[which(long_dat$threatlevel == unique(long_dat$threatlevel)[i]),])
  coo_threat[i,2] <-coef(m)[1]
  coo_threat[i,3] <- confint(m)[1]
  coo_threat[i,4] <- confint(m)[2]
}

##theme for plotting

raincloud_theme = theme(
  text = element_text(size = 10),
  axis.title.x = element_text(size = 16),
  axis.title.y = element_text(size = 16),
  axis.text = element_text(size = 14),
  axis.text.x = element_text(angle = 45, vjust = 0.5),
  legend.title=element_text(size=16),
  legend.text=element_text(size=16),
  legend.position = "right",
  plot.title = element_text(lineheight=.8, face="bold", size = 16),
  panel.border = element_blank(),
  panel.grid.minor = element_blank(),
  panel.grid.major = element_blank(),
  axis.line.x = element_line(colour = 'black', size=0.5, linetype='solid'),
  axis.line.y = element_line(colour = 'black', size=0.5, linetype='solid'))

#barlot

#reorder threats
coo_threat$threat_status <- factor(coo_threat$threat_status, levels = rev(c("LC","NT","VU","EN","CR","EX")))
colnames(long_dat)[14]<-"threat_status"

g <- ggplot() +
  geom_bar( data = coo_threat, aes(x = threat_status , y = mean), stat="identity", fill="forestgreen", alpha=0.5) +
  geom_pointrange(data = coo_threat, aes(x = threat_status ,ymin = low_cl, ymax = up_cl, y = mean)) +
  geom_hline(yintercept=1.34,linetype="dashed")+
  geom_hline(yintercept=0,linetype="solid")+
  ylab("Co-occurence clustering")+
  xlab("")+
  theme_bw() +
  raincloud_theme


