# =========================
# PACOTES
# =========================
library(sf)
library(dplyr)
library(ggplot2)
library(readxl)
library(patchwork)
library(scales)
# =========================
# LEITURA DOS DADOS CLIMÁTICOS
# =========================
dados_tab <- read_excel("dados_climaticos2.xlsx")
# =========================
# LEITURA + CORREÇÃO + SIMPLIFICAÇÃO DO SHAPE
# (VERSÃO ESTÁVEL – SEM rmapshaper / V8)
# =========================
shape_mun <- st_read(
"BR_Municipios_2025.shp",
quiet = TRUE
) |>
st_transform(4326) |>
st_make_valid() |>
st_simplify(
dTolerance = 0.01,
preserveTopology = TRUE
)
# =========================
# JOIN ENTRE GEOMETRIA E DADOS CLIMÁTICOS
# =========================
dados_sf <- shape_mun |>
left_join(
dados_tab,
by = c("NM_MUN", "NM_UF")
) |>
select(
NM_MUN,
NM_UF,
YEAR,
trimestre,
spi
)
# =========================
# FUNÇÃO DE MAPA SPI (SEM LIMITES)
# =========================
mapa_spi <- function(df, titulo) {
ggplot(df) +
geom_sf(
aes(fill = spi),
color = NA
) +
scale_fill_distiller(
palette = "RdBu",
limits = c(-2, 2),
oob = squish,
direction = -1
) +
labs(
title = titulo,
fill = "SPI"
) +
theme_minimal()
}
# =========================
# FUNÇÃO PARA MAPAS TRIMESTRAIS POR ANO
# =========================
plot_ano <- function(ano) {
df_ano <- dados_sf |>
filter(YEAR == ano)
plots <- lapply(
sort(unique(df_ano$trimestre)),
function(t) {
mapa_spi(
df_ano |> filter(trimestre == t),
paste("SPI -", t, "/", ano)
)
}
)
wrap_plots(plots, ncol = 2)
}
# =========================
# EXECUÇÃO
# =========================
plot_ano(2025)





