rm(list=ls(all=TRUE))                                 # Limpa memória
gc()
# Define working directory
setwd("/cloud/project/LCF5900")

# Load packages
if(!require(tidyverse))
  install.packages("tidyverse")
library(tidyverse)

if(!require(gganimate))
  install.packages("gganimate")
library(gganimate)

# Define github URL where climate data from Piracicaba is stored
url_1 <- "https://github.com/FlorestaR/dados/blob/main/X_PIRACLIM"
xls_2 <- "DadosClima_Piracicaba.csv"
prm_3 <- "?raw=true"
gitFile <- file.path(url_1, xls_2) %>% paste0(prm_3)

# Downloads Excel table as a tibble (dataframe) from github
df <- read.csv(gitFile, sep=";")  %>% tibble()                 # import

# Show column names and first rows from the table
colnames(df)
head(df)
tail(df)

df <- df %>%
  select(ANO, MES, TMED, TMIN, TMAX, Chuva, Estiagem) %>%
  drop_na() %>%
  mutate_if(is.character,as.numeric) %>%
  filter(TMED <50)
str(df)

df %>% summarise(m_TMED     = mean(TMED),
                 m_TMIN     = mean(TMIN),
                 m_TMAX     = mean(TMAX),
                 m_Chuva    = mean(Chuva),
                 m_Estiagem = mean(Estiagem))

medMes <- group_by(df, ANO, MES) %>% summarise(tmedMes = mean(TMED))

p <- ggplot(medMes, aes(medMes$MES, medMes$tmedMes)) +
  geom_point() +
  # geom_smooth(⁠method = "gam", formula = y ~ s(x, bs = "cs")⁠) +
  ggtitle("{frame_time}") +
  transition_time(as.integer(medMes$ANO)) +
  ease_aes("linear") +
  enter_fade() +
  exit_fade()

animate(p, width = 750, height = 450)
anim_save(p, "grafGIF.gif")

animate(p, renderer = ffmpeg_renderer(), width = 800, height = 450)
anim_save("animGraf.mp4")