'
Creates the deforestation Supplementary Figure SI1 of the paper. Uses deforestation and fire data
from "original_data" and saves the plot as a png file to "bld/figures/".

'

rm(list = ls())
options(scipen = 999)
options(warn = -1) # 0 to turn on again
source(paste0("src/code/ggplot_theme_publication.r")) # Load a user-written ggplot theme and style.

# Load libraries
library(tidyverse) # More intuitive data wrangling
library(Cairo)

# Load deforestation data for Legal Amazon and prepare it for plotting.
deforestation <- read.csv(paste0("src/original_data/terrabrasilis_deforestation_legal_amazon.csv"), sep = ";")
colnames(deforestation)[2] <- "area"
deforestation <- deforestation %>%
  mutate(area = as.numeric(gsub(",", "", area))) %>%
  rename(value = area)
deforestation$legend <- "Deforestation"
deforestation <- deforestation[deforestation$year > 2002 & deforestation$year < 2018, ]

# Load fire number data for Legal Amazon and prepare it for plotting
fires <- readRDS(paste0("src/original_data/inpe_fires_legal_amazon.RDS"))
fires$legend <- "Fires"
fires$fires <- fires$fires / 10 # Divide by 10 for figure scaling purposes. Number of fires will be correct in figure
fires <- fires %>% rename(value = fires)
fires <- fires[fires$year > 2002 & fires$year < 2018, ]

# Append both dataset together
#bla <- rbind.data.frame(deforestation, fires)



# Plot the figure
cols <- c("Fires" = "#f87f01")
fils <- c("Deforestation" = "#cccccc")
p <- ggplot() +
  geom_bar(stat = "identity", aes(x = deforestation$year, y = deforestation$value, fill = "Deforestation"), colour="#333333") +
  geom_line(mapping = aes(x = fires$year, y = fires$value, colour = "Fires"), size = 1.1) +
  # geom_point(mapping = aes(x = fires$year, y = fires$value), size = 0.8) +
  xlab("Year") +
  scale_x_continuous(breaks = 2003:2017) + 
  scale_y_continuous(
    name = expression(paste("Deforestation (km"^2,")")),
    labels = scales::comma,
    sec.axis = sec_axis(~.*10, name = "Number of fires",
    labels = function(b) {paste0(b); format(b, big.mark = ",", decimal.mark = ".", scientific = FALSE)})) +
  scale_colour_manual(values = cols) +
  scale_fill_manual(values = fils) +
  theme_Publication() + 
  theme(
    legend.title = element_blank(),
    axis.text.x = element_text(angle = 45, hjust = 1))

p

# Save it 
ggsave(plot = p, filename = "bld/figures/bla_historic_deforestation.pdf", device = cairo_pdf, height = 9, width = 15, units = "cm")

