d <- rgdal::readOGR("allplots.geojson")
## OGR data source with driver: GeoJSON 
## Source: "C:\Users\rnussba1\OneDrive\OneDrive - ARK\dakatcha_deforestation\GEE_analysis\allplots.geojson", layer: "allplots"
## with 29 features
## It has 7 fields, of which 2 list fields
d$acquired = dmy(d$acquired)
pal = colorNumeric(palette = 'viridis', domain=c(as.numeric(as_date("2014-01-01")),as.numeric(as_date("2022-01-01"))))#range(as.numeric(d$acquired),na.rm=T)
pal2 = colorNumeric(palette = 'viridis', domain=c(14,22), na.color = "transparent")


leaflet(d, width ='100%') %>%
  addProviderTiles('Esri.WorldImagery') %>%
  addRasterImage(raster("deforestation.tif"), colors = pal2, opacity = 1) %>% 
  addPolygons(fillOpacity = 0,
              opacity = 1,
              color = ~pal(as.numeric(acquired)),
              popup = ~paste0('<b>Name:</b> ', Name,'<br>',
                              '<b>Status:</b> ', Status,'<br>',
                              '<b>Acquired date:</b> ', acquired),
              ) %>% 
  addLegend("bottomright", pal = pal, values = seq(min(as.numeric(d$acquired),na.rm=T)+1, max(as.numeric(d$acquired),na.rm=T),length.out=10), 
             title = "Date", opacity = 1,
            labFormat = labelFormat(transform = function(x) as_date(x))) %>%
    addFullscreenControl()
dd <- as.data.frame(d) %>% 
  gather('year','deforestion_sum',cumulated1:cumulated21) %>%
  gather('year2','deforestion',data1:data21) %>% 
  mutate(
    Status = ifelse(Status==0,NA,Status),
    year = as.numeric(str_remove(year,'cumulated'))+1999,
    year2 = as.numeric(str_remove(year2,'data'))+1999,
  ) %>% 
  filter(year==year2) %>%
  dplyr::select(-c(id,year2))
  

(dd %>% 
    mutate(label = paste0(Name,' (',acquired,')'))%>% 
    ggplot() +
    geom_line(aes(x=year, y=deforestion_sum, group=label,colour = acquired)) +
    theme_bw()
  ) %>% ggplotly(width=910)