Parte 1: Acadêmica

Row

Ex 1.1: Scatter Plot (mtcars)

Ex 1.2: Bar Plot (diamonds)

Row

Ex 1.3: Boxplot Customizado

Ex 1.4: Conceitos Teóricos

Gramática dos Gráficos: Camadas independentes (Dados + Estética + Geometria). Geom Point vs Jitter: Point sobrepõe dados iguais; Jitter espalha para mostrar densidade.

Parte 2: Criminalidade MG (Aplicada)

Row

Total Homicídios

5252

Veículos Roubados

9218

Municípios

676

Row

Evolução Temporal

Top 10 Municípios (Homicídios)

Row

Ocorrências por RISP

Dados Detalhados

---
title: "Prova Visualização de Dados :: Relatório de Análise de Dados"
author: "Aluisio Martins Junior - 127.375-4"
output:
  flexdashboard::flex_dashboard:
    logo: logo_pmmg.png
    orientation: rows
    vertical_layout: fill
    theme: cerulean
    source_code: embed
    css: styles.css
---

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

# Configuração Global
knitr::opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE)

# --- CONFIGURAÇÃO DE AMBIENTE E CARGA ---

# Força o diretório de trabalho para onde seus dados estão (Hardcoded para sua máquina)
caminho_dados <- "D:/facul/Prova_Final_CienciaDados/"

if (dir.exists(caminho_dados)) {
  setwd(caminho_dados)
}

# Tratamento de erro robusto
tryCatch({
  
  # Carregar Homicídios
  df_hom <- read.csv2("D:/facul/Prova_Final_CienciaDados/homicidios.csv", fileEncoding = "utf8", check.names = FALSE, header = TRUE) %>%
    clean_names() %>%
    mutate(
      data_fato = dmy(data_fato), # converter DD/MM/AAAA
      categoria = "Homicídio Consumado",
      qtd = 1
    ) %>%
    filter(!is.na(data_fato)) # Remove erros de conversão de data

  # Carregar Roubo de Veículos
  df_roubo <- read.csv2("D:/facul/Prova_Final_CienciaDados/roubo_veiculos.csv", fileEncoding = "utf8", check.names = FALSE, header = TRUE) %>%
    clean_names() %>%
    mutate(
      data_fato = ymd(data_fato), # Tenta converter AAAA-MM-DD
      categoria = "Roubo de Veículos"
    ) %>%
    rename(qtd = qtde_veiculos) %>%
    filter(!is.na(data_fato))

  # Unificar Bases
  # Definir janela de tempo (últimos 24 meses dos dados disponíveis)
  data_max <- max(c(df_hom$data_fato, df_roubo$data_fato), na.rm = TRUE)
  data_min <- data_max %m-% months(24)

  df_consolidado <- bind_rows(
    df_hom %>% select(data_fato, municipio, risp, qtd, categoria),
    df_roubo %>% select(data_fato, municipio, risp, qtd, categoria)
  ) %>%
    filter(data_fato >= data_min) %>%
    mutate(mes_ano = floor_date(data_fato, "month"))
    
}, error = function(e) {
  # Fallback se der erro na leitura (Cria dados fake pra não mostrar o dashboard vazio)
  df_consolidado <<- data.frame(
    municipio = c("ERRO: Verifique CSVs"),
    qtd = 0,
    categoria = "Erro",
    mes_ano = Sys.Date(),
    risp = "Erro"
  )
  print(e) # Imprime o erro no console
})

```

# Parte 1: Acadêmica

## Row {data-height="400"}

### Ex 1.1: Scatter Plot (mtcars)

```{r}
p1 <- ggplot(data = mtcars, aes(x = wt, y = mpg, color = factor(cyl))) + 
  geom_point(size = 3, alpha = 0.8) +
  labs(title = "Peso x Consumo", x = "Peso", y = "MPG", color = "Cilindros") +
  theme_minimal()
ggplotly(p1)

```

### Ex 1.2: Bar Plot (diamonds)

```{r}
p2 <- diamonds %>%
  count(cut) %>%
  ggplot(aes(x = reorder(cut, -n), y = n, fill = cut)) +
  geom_bar(stat = "identity") +
  scale_fill_brewer(palette = "RdBu") +
  labs(title = "Diamantes por Corte", x = "Corte", y = "Qtd") +
  theme_minimal() + theme(legend.position = "none")
ggplotly(p2)

```

## Row {data-height="400"}

### Ex 1.3: Boxplot Customizado

```{r}
p3 <- ggplot(diamonds, aes(x = cut, y = price, fill = cut)) +
  geom_boxplot() +
  labs(title = "Distribuição de Preços", x = "Corte", y = "Preço ($)") +
  theme_minimal() + theme(axis.text.x = element_text(angle = 45))
ggplotly(p3)

```

### Ex 1.4: Conceitos Teóricos

**Gramática dos Gráficos:** Camadas independentes (Dados + Estética + Geometria). **Geom Point vs Jitter:** Point sobrepõe dados iguais; Jitter espalha para mostrar densidade.

# Parte 2: Criminalidade MG (Aplicada)

## Row {data-height="150"}

### Total Homicídios

```{r}
v <- df_consolidado %>% filter(categoria == "Homicídio Consumado") %>% pull(qtd) %>% sum()
valueBox(v, icon = "fa-skull", color = "#BF3F3F")

```

### Veículos Roubados

```{r}
v <- df_consolidado %>% filter(categoria == "Roubo de Veículos") %>% pull(qtd) %>% sum()
valueBox(v, icon = "fa-car", color = "#F29849")

```

### Municípios

```{r}
v <- n_distinct(df_consolidado$municipio)
valueBox(v, icon = "fa-map-marker", color = "primary")

```

## Row {data-height="450"}

### Evolução Temporal

```{r}
df_time <- df_consolidado %>%
  group_by(mes_ano, categoria) %>%
  summarise(total = sum(qtd), .groups = 'drop')

p_time <- ggplot(df_time, aes(x = mes_ano, y = total, color = categoria)) +
  geom_line(size = 1) + geom_point() +
  theme_minimal()
ggplotly(p_time)

```

### Top 10 Municípios (Homicídios)

```{r}
p_bar <- df_consolidado %>%
  filter(categoria == "Homicídio Consumado") %>%
  group_by(municipio) %>%
  summarise(total = sum(qtd)) %>%
  top_n(10, total) %>%
  ggplot(aes(x = reorder(municipio, total), y = total)) +
  geom_bar(stat = "identity", fill = "darkred") +
  coord_flip() + theme_minimal()
ggplotly(p_bar)

```

## Row {data-height="450"}

### Ocorrências por RISP

```{r}
df_risp <- df_consolidado %>%
  group_by(risp, categoria) %>%
  summarise(total = sum(qtd), .groups = 'drop')
p_risp <- ggplot(df_risp, aes(x = reorder(risp, total), y = total, fill = categoria)) +
  geom_bar(stat = "identity", position = "dodge") +
  coord_flip() + theme_minimal()
ggplotly(p_risp)

```

### Dados Detalhados

```{r}
df_table <- df_consolidado %>%
  group_by(municipio, categoria) %>%
  summarise(total = sum(qtd), .groups = 'drop') %>%
  pivot_wider(names_from = categoria, values_from = total, values_fill = 0)
datatable(df_table, options = list(pageLength = 5, scrollY = "200px"))

```