
#Figure 3: Niche overlap calculation and visualization (M vs F)

# load packages
library(dplyr)
library(rKIN)
library(ggplot2)

iso_dat <- read.csv(file.choose())
iso_clean <- iso_dat
iso_clean$Sex[!(iso_clean$Sex %in% c("M", "F"))] <- NA
iso_clean$Sex <- factor(iso_clean$Sex, levels = c("M", "F"))
#keep only adult individuals
iso_clean<-iso_clean%>%filter(Age_bin=="a")

## keep only individuals with complete observatons (adapt accordimg to element to explore) 
iso_clean <- iso_clean[
  !is.na(iso_clean$d13C) & !is.na(iso_clean$d15N),
]


iso_cn <- iso_clean[
  !is.na(iso_clean$Sex),    
]

# Kernel isotope niche estimation (d13C, d15N, by sex: adapt if necessary) 

kin_sex <- estKIN(
  data   = iso_cn,
  x      = "d13C",          
  y      = "d15N",          
  group  = "Sex",           
  levels = c(50, 75, 95),   
  scaler = 2                
)

## Niche area (by sex and CI)
kin_area <- getArea(kin_sex)
kin_area

## Niche overlap (by sex and CI)

kin_olp <- calcOverlap(kin_sex)

## Plot results (remember to adapt according to chosen elements!!!)

plotKIN(
  kin_sex,
  title = "Kernel isotopic niches in CN space by sex",
  xlab  = expression(delta^13*C~"\u2030"),
  ylab  = expression(delta^34*S~"\u2030"))








