#Figuras KDE
rm(list=ls()) ## Removendo as variáveis
gc()
packages<-c('ggplot2','reshape','sf','raster')
package.check <- lapply(packages, FUN = function(x) {
  if (!require(x, character.only = TRUE)) {
    install.packages(x, dependencies = TRUE)
    library(x, character.only = TRUE)
  }
})

load('output_data/kde_all_NE_v4.Rda')
plot(kde_all)

#Figuras pesca industrial-----
# load('output_data/kde_all.Rda')

mapWorld <- borders("world", colour="gray50", fill="gray50", alpha=.7) # create a layer of borders
isobath<-read_sf("/home/gandra/Dropbox/tese_final/shapes/isobatas_utm.shp", "isobatas_utm")
plot(isobath)
isobath_df<-fortify(isobath)


bed_wgs<-projectRaster(kde_all,crs="+init=epsg:4326")
hist(bed_wgs$Armadilha)
hist(bed_wgs$Espinhel)
preps_clip<-bed_wgs>=0.1
plot(preps_clip)
preps_all<-sum(preps_clip)
plot(preps_all)
preps_all<-projectRaster(preps_all,crs="+init=epsg:5641")
writeRaster(preps_all,"~/github/ei_turtles/input_data/preps_v4.tif",overwrite=T)
res(bed_wgs)
#Convertendo raster to points
be.p <- rasterToPoints(bed_wgs)

#Make the points a dataframe for ggplot
be.df <- data.frame(be.p)

minlon<-min(be.df$x-0.2)
maxlon<-max(be.df$x+0.2)
minlat<-min(be.df$y-0.2)
maxlat<-max(be.df$y+0.2)

d<-melt(be.df,id=c('x','y'))

d<-d[d$value>=0.01,]

ggplot()+
  geom_raster(data=d,aes(y=y,x=x, fill=value))+theme_bw()+
  # geom_path(data = isobath_df, 
  #           aes(x = long, y = lat, group = group),
  #           linetype = "dashed", size = .2)+
  facet_wrap(~variable, ncol=2, shrink=T)+
  coord_equal(xlim = c(minlon, maxlon),ylim = c(minlat, maxlat))+
  ylab(NULL)+
  scale_fill_distiller(palette = "Spectral")+
  theme_bw() +
  theme(legend.position="none",
        strip.text.x = element_text(size = 8),
        axis.title=element_blank(),
        axis.text=element_blank(),
        axis.ticks=element_blank(),
        line=element_blank())+
  mapWorld
ggsave('figures/heatmaps.jpg',width=14, height = 16, units = 'cm', dpi=300)
