Row

Total de Vítimas (24 Meses)

5493

Row

Ranking: Cidades com Homicídios (Últimos 24 Meses)

Row

Painel Geral de Gráficos (4 Visualizações)

Row

Mapa de Calor (Homicídios por Município)

Mapa por Região (RISP/RPM)

---
title: "PMMG - VÍTIMAS DE HOMICÍDIO CONSUMADO MG"
output: 
  flexdashboard::flex_dashboard:
    orientation: rows
    vertical_layout: scroll
    theme: yeti
    source_code: embed
    logo: logo_pmmg.png
---

<style>
.navbar-brand {
  display: flex;
  align-items: center;
}
.navbar-logo {
  height: 40px !important;  
  width: auto !important;   
  margin-right: 10px;       
}
</style>

```{r setup, include=FALSE}
library(flexdashboard)
library(tidyverse)
library(readxl)
library(plotly)
library(DT)
library(leaflet)
library(sf)
library(janitor)
library(lubridate)
library(dplyr)


arquivo_nome <- "dados.csv"


dados_brutos <- read.csv2(arquivo_nome, fileEncoding = "latin1", stringsAsFactors = FALSE) %>% 
  clean_names()



d <- read.csv2("dados.csv", fileEncoding = "UTF-8")
names(d)

```
Row
-----------------------------------------------------------------------

### Total de Vítimas (24 Meses)

```{r}

library(stringr)

d_cards <- d %>% 
  mutate(Data_Temp = make_date(year = Ano, month = Mês, day = 1))

data_max <- max(d_cards$Data_Temp, na.rm = TRUE)
d_cards_filtro <- d_cards %>% 
  filter(Data_Temp >= (data_max - months(24)), 
         Registros > 0, 
         str_detect(Natureza, "Homicídio"))

total <- sum(d_cards_filtro$Registros, na.rm = TRUE)
media <- round(mean(d_cards_filtro$Registros, na.rm = TRUE), 1)
pior_cidade <- d_cards_filtro %>% 
  group_by(Município) %>% 
  summarise(Total = sum(Registros)) %>% 
  arrange(desc(Total)) %>% 
  slice(1) %>% 
  pull(Município)


valueBox(total, icon = "fa-skull-crossbones", color = "danger")
```


Row
-----------------------------------------------------------------------

### Ranking: Cidades com Homicídios (Últimos 24 Meses)

```{r}

d_processada <- d %>% 
  mutate(Data_Completa = make_date(year = Ano, month = Mês, day = 1))


data_maxima <- max(d_processada$Data_Completa, na.rm = TRUE)
data_corte <- data_maxima - months(24)


d_filtrada <- d_processada %>% 
  filter(
    Data_Completa >= data_corte,          
    Registros > 0,                        
    str_detect(Natureza, "Homicídio")     
  )


ranking_cidades <- d_filtrada %>%
  group_by(Município) %>%
  summarise(
    Total_Homicidios = sum(Registros, na.rm = TRUE),
    Media_Mensal = round(mean(Registros, na.rm = TRUE), 1)
  ) %>%
  arrange(desc(Total_Homicidios)) 


datatable(ranking_cidades,
          caption = "Municípios com Homicídios registrados nos últimos 24 meses",
          rownames = FALSE)

```
Row {data-height=700}
-----------------------------------------------------------------------

### Painel Geral de Gráficos (4 Visualizações)

```{r}
library(ggplot2)
library(plotly)



# G1: Evolução Temporal
g1 <- d_filtrada %>%
  group_by(Data_Completa) %>%
  summarise(Total = sum(Registros, na.rm = TRUE)) %>%
  ggplot(aes(x = Data_Completa, y = Total)) +
  geom_line(color = "#2980b9") +
  geom_point(color = "red") +
  theme_minimal() +
  labs(x = "", y = "Homicídios", title = "Evolução")

# G2: Top 10 Cidades
top_cidades <- d_filtrada %>%
  group_by(Município) %>%
  summarise(Total = sum(Registros, na.rm = TRUE)) %>%
  arrange(desc(Total)) %>%
  slice(1:10)

g2 <- ggplot(top_cidades, aes(x = reorder(Município, Total), y = Total)) +
  geom_col(fill = "firebrick") +
  coord_flip() +
  theme_minimal() +
  labs(x = "", y = "", title = "Top 10 Cidades")

# G3: Região (Capital vs Interior)
g3 <- d_filtrada %>%
  group_by(RMBH) %>%
  summarise(Total = sum(Registros, na.rm = TRUE)) %>%
  ggplot(aes(x = RMBH, y = Total, fill = RMBH)) +
  geom_col() +
  scale_fill_manual(values = c("gray", "orange")) +
  theme_minimal() +
  theme(legend.position = "none") + # Remove legenda para limpar
  labs(x = "", y = "Total", title = "Região (RMBH)")

# G4: Sazonalidade (Mês)
g4 <- d_filtrada %>%
  group_by(Mês) %>%
  summarise(Total = sum(Registros, na.rm = TRUE)) %>%
  ggplot(aes(x = factor(Mês), y = Total)) +
  geom_col(fill = "#27ae60") +
  theme_minimal() +
  labs(x = "Mês", y = "", title = "Por Mês")

# --- 2. CONVERTER PARA PLOTLY ---
p1 <- ggplotly(g1)
p2 <- ggplotly(g2)
p3 <- ggplotly(g3)
p4 <- ggplotly(g4)


subplot(p1, p2, p3, p4, nrows = 2, margin = 0.04, titleX = TRUE, titleY = TRUE)

```
Row {data-height=600}
-----------------------------------------------------------------------

### Mapa de Calor (Homicídios por Município)

```{r}

.libPaths(c("D:/R_libs", .libPaths()))
options(geobr.cache_dir = "D:/geobr_cache")

library(geobr)
library(sf)
library(leaflet)
library(janitor) 

# 1. Baixar Mapa de MG
mg_mapa <- read_municipality(code_muni = "MG", year = 2020, showProgress = FALSE)


d_segura <- d_filtrada %>% 
  clean_names() 

dados_mapa <- d_segura %>%
  group_by(cod_ibge) %>%  
  summarise(Total = sum(registros, na.rm = TRUE))


mg_mapa <- mg_mapa %>%
  mutate(cod_join = as.numeric(substr(code_muni, 1, 6)))


mapa_final <- mg_mapa %>%
  left_join(dados_mapa, by = c("cod_join" = "cod_ibge"))


mapa_final$Total[is.na(mapa_final$Total)] <- 0


paleta <- colorBin(
  palette = c("#228B22", "#FFD700", "#FF8C00", "#FF0000", "#8B0000"), 
  domain = mapa_final$Total,
  bins = 5, # Divide em 5 faixas de intensidade
  na.color = "transparent"
)


leaflet(mapa_final) %>%
  addTiles() %>%
  addPolygons(
    fillColor = ~paleta(Total),
    weight = 1, 
    color = "white", 
    fillOpacity = 0.8,
    label = ~paste0(name_muni, ": ", Total, " vítimas"),
    popup = ~paste0("Município: ", name_muni, "<br>Total: ", Total)
  ) %>%
  addLegend(pal = paleta, values = ~Total, opacity = 0.7, title = "Vítimas", position = "bottomright")
  
```

### Mapa por Região (RISP/RPM)

```{r}

library(janitor)


dados_risp <- d_filtrada %>%
  clean_names() %>%          
  group_by(risp) %>%         
  summarise(Total_RISP = sum(registros, na.rm = TRUE))


relacao_cidade_risp <- d_filtrada %>%
  clean_names() %>%
  select(cod_ibge, risp) %>%
  distinct() 

mapa_risp_final <- mg_mapa %>%
  #
  mutate(code_muni_6 = as.numeric(substr(code_muni, 1, 6))) %>%
  left_join(relacao_cidade_risp, by = c("code_muni_6" = "cod_ibge")) %>%
  left_join(dados_risp, by = "risp")


paleta_risp <- colorNumeric(palette = "Blues", domain = mapa_risp_final$Total_RISP)


leaflet(mapa_risp_final) %>%
  addProviderTiles(providers$CartoDB.Positron) %>% # Fundo mais limpo
  addPolygons(
    fillColor = ~paleta_risp(Total_RISP),
    weight = 0.5, 
    color = "white", 
    fillOpacity = 0.8,
    label = ~paste0(risp, ": ", Total_RISP),
    popup = ~paste0("<strong>Região:</strong> ", risp, "<br><strong>Total RISP:</strong> ", Total_RISP)
  )
```