Visualizaciones reactivas

Warning: package 'rsconnect' was built under R version 4.3.3

Attaching package: 'shiny'
The following object is masked from 'package:rsconnect':

    serverInfo

Attaching package: 'plotly'
The following object is masked from 'package:ggplot2':

    last_plot
The following object is masked from 'package:stats':

    filter
The following object is masked from 'package:graphics':

    layout

Attaching package: 'dplyr'
The following objects are masked from 'package:stats':

    filter, lag
The following objects are masked from 'package:base':

    intersect, setdiff, setequal, union
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ forcats   1.0.0     ✔ stringr   1.5.1
✔ lubridate 1.9.3     ✔ tibble    3.2.1
✔ purrr     1.0.2     ✔ tidyr     1.3.0
✔ readr     2.1.4     
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks plotly::filter(), stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
Warning: package 'sf' was built under R version 4.3.3
Linking to GEOS 3.11.2, GDAL 3.8.2, PROJ 9.3.1; sf_use_s2() is TRUE

Edad de la Víctimas Fatales

library(readxl)
Descarga_Sigisvi <- read_excel("Descarga_Sigisvi.xlsx", 
    sheet = "Personas")

Personas <- Descarga_Sigisvi

G8 <- Personas %>% 
  filter((edad <= 98) & (tipo_involucrado == "Automóvil" | tipo_involucrado == "Motocicleta" | tipo_involucrado == "Peatón" |
           tipo_involucrado == "Transporte de carga" | tipo_involucrado == "Camioneta/Utilitario" | 
           tipo_involucrado == "Bicleta") & (genero == "Masculino" | genero == "Femenino") &
           (estado_ocupante_final != "S/D"))

G8$edad <- as.numeric(G8$edad) #edad numérico
G8$tipo_involucrado <- as.factor(G8$tipo_involucrado) # involucrado como factor

G8 <- na.omit(G8[, c("tipo_involucrado", "genero", "edad", "estado_ocupante_final")])
# Asegúrate de que 'genero' esté correctamente codificado
G8$genero <- as.factor(G8$genero)
G8$genero <- factor(G8$genero, levels = unique(G8$genero))

# Asegúrate de que 'tipo_involucrado' esté correctamente codificado
G8$tipo_involucrado <- as.factor(G8$tipo_involucrado)
G8$tipo_involucrado <- factor(G8$tipo_involucrado, levels = unique(G8$tipo_involucrado))

# Crear los selectores con "Todos" como opción por defecto
selectInput("ti", label = "Tipo de vehículo:",
            choices = c("Todos", levels(G8$tipo_involucrado)),
            selected = "Todos")
selectInput("genero", label = "Género:",
            choices = c("Todos", levels(G8$genero)),
            selected = "Todos")
# Generar el gráfico filtrando según las selecciones
renderPlotly({
  filtered_data <- G8
  
  # Filtrar por tipo de vehículo si no es "Todos"
  if (input$ti != "Todos") {
    filtered_data <- filtered_data %>% filter(tipo_involucrado == input$ti)
  }
  
  # Filtrar por género si no es "Todos"
  if (input$genero != "Todos") {
    filtered_data <- filtered_data %>% filter(genero == input$genero)
  }

  # Crear el gráfico
  p25 <- ggplot(data = filtered_data) +
    geom_histogram(binwidth = 1, aes(x = edad), fill = "#c74946", color="#bec092") + 
    xlab("Edad") + 
    ylab("Víctimas") + 
    ggtitle("Edad de las Víctimas registradas (2022)") +
    theme_grey() +
    facet_wrap("estado_ocupante_final", scales = "free")

  ggplotly(p25)
})

Víctimas Fatales por Horario y Día

# Leer el archivo Excel
hora_2022 <- read_excel("hora_2022.xlsx")

# Convertir siniestro_hora a formato POSIXct y extraer la hora
hora_2022 <- hora_2022 %>%
  mutate(
    siniestro_hora = as.POSIXct(siniestro_hora, format = "%H:%M:%S"),  # Convertir a formato POSIXct
    intervalo2 = format(siniestro_hora, format = "%H")  # Extraer solo la hora
  )

# Crear la variable de días de la semana
hora_2022 <- hora_2022 %>%
  mutate(dias_n = weekdays(siniestro_fecha))

# Contar el número de fallecidos por intervalo2 y días de la semana
hora_2022 <- hora_2022 %>% 
  count(intervalo2, dias_n) 

# Renombrar la columna de conteo a "Fallecidos"
hora_2022 <- rename(hora_2022, Fallecidos = n)

# Agrupar por intervalo2 y sumar fallecidos
hora_2022_b <- hora_2022 %>% 
  group_by(intervalo2) %>% 
  summarise(F = sum(Fallecidos))

# Eliminar filas con NA en intervalo2
hora_2022_b <- hora_2022_b[!is.na(hora_2022_b$intervalo2), ]

# Convertir intervalo2 a factor
hora_2022$intervalo2 <- as.factor(hora_2022$intervalo2)

# Crear la aplicación Shiny
shinyApp(
  ui = fluidPage(
    selectInput("dias", label = "Días de la semana:",
                choices = c("Todos", rev(unique(hora_2022$dias_n))),
                selected = "Todos"),
    plotOutput("horaPlot")
  ),
  
  server = function(input, output) {
    output$horaPlot <- renderPlot({
      filtered_data <- if(input$dias == "Todos") {
        hora_2022
      } else {
        hora_2022 %>% filter(dias_n == input$dias)
      }
      
      ggplot(data = filtered_data) +
        geom_bar(mapping = aes(x = factor(intervalo2), y = Fallecidos),
                 stat = "identity", color = "grey", fill = "#37BBED") +
        coord_polar(theta = "x", start = -0.1, direction = 1, clip = "on") +
        labs(title = "Concentración de casos por hora",
             x = "", 
             y = "Fallecidos") +
        theme_minimal() +
        theme(axis.text.x = element_text(angle = 0, hjust = 0),
              legend.position = "none") 
    })
  }
)

Tipo de Víctima según vehículo y vía

# Leer el archivo CSV
Personas <- read_csv("Personas.csv")
New names:
Rows: 46925 Columns: 102
── Column specification
──────────────────────────────────────────────────────── Delimiter: "," chr
(72): sumario_policial, expediente_judicial, dependencia, unidad_region... dbl
(17): ...1, numero_formulario, dia, mes, ano, id_provincia, latitud, lo... lgl
(9): codigo_gobierno_local, trazado_via, pendiente_declive, transito_r... date
(3): siniestro_fecha, nacimiento_fecha, fecha_fin_seguimiento time (1):
siniestro_hora
ℹ Use `spec()` to retrieve the full column specification for this data. ℹ
Specify the column types or set `show_col_types = FALSE` to quiet this message.
• `` -> `...1`
# Filtrar los datos según los criterios especificados
Personas <- Personas %>% 
  filter((estado_ocupante_final == "Fallecido" | estado_ocupante_final == "Fallecido a 30 días" |
            estado_ocupante_final == "Herido Grave") &
           (tipo_involucrado == "Automóvil" | tipo_involucrado == "Motocicleta" | tipo_involucrado == "Peatón" |
              tipo_involucrado == "Transporte de carga" | tipo_involucrado == "Bicicleta"))

# Crear la aplicación Shiny
shinyApp(
  ui = fluidPage(
    fluidRow(
      column(
        width = 12,
        selectInput("via", label = "Vía Pública:",
                    choices = c("Todos", unique(Personas$via_publica)),
                    selected = "Todos"),
        plotlyOutput("mosaicoPlot", height = "100vh")  # Altura del gráfico en 100% del viewport
      )
    )
  ),
  
  server = function(input, output) {
    output$mosaicoPlot <- renderPlotly({
      filtered_data <- if(input$via == "Todos") {
        Personas
      } else {
        Personas %>% filter(via_publica == input$via)
      }
      
      Mosaico <- ggplot(filtered_data) +
        geom_mosaic(aes(x = product(tipo_involucrado), fill = estado_ocupante_final)) +
        labs(title = "Lesionados según tipo de vehículo - Año 2022", 
             caption = "Fuente: ANSV",
             y = "Lesionados",
             x = "Vehículos") +
        scale_fill_manual(values = c("#56B4E9", "#009E73", "#E69F00"))
      
      ggplotly(Mosaico)
    })
  }
)

Mapa de tasa de Mortalidad

mapa1 <- st_read("Provincias_t.shp", quiet = TRUE)
specify_decimal <- function(TM, k) trimws(format(round(TM, k), nsmall = k))
popup <- paste0("<b>", "Provincia: ", "</b>", as.character(mapa1$PROVINCIA),"<br>", 
    "<b>",  "Tasa de Mortalidad c/100 mil hab.: ", "</b>", as.numeric(mapa1$TM), "<br>")


pal2 <- colorNumeric(
  c("#A9A9A9","#EDC9DF", "#E3ADD0", "#D177B0", "#B83E8B", "#7B295D"),
  # colors depend on the count variable
  domain = mapa1$TM,
  )

# Crear la aplicación Shiny
shinyApp(
  ui = fluidPage(
    leafletOutput("map"),
    div(
      selectInput("provincia", "Selecciona una provincia:", choices = unique(mapa1$PROVINCIA)),
      style = "position: fixed; top: 0; width: 100%;"
    )
  ),
  server = function(input, output, session) {
    
    # Crear el mapa
    output$map <- renderLeaflet({
      provincia_selected <- input$provincia
      
      if (is.null(provincia_selected)) {
        provincia_selected <- unique(mapa1$PROVINCIA)[1]
      }
      
      filtered_data <- mapa1[mapa1$PROVINCIA == provincia_selected, ]
      
      leaflet(filtered_data, options = leafletOptions(zoomControl = FALSE)) %>% # para sacarle el boton +/-
        addProviderTiles("CartoDB") %>%
        addPolygons(
          color = "#444444" ,
          weight = 1, 
          smoothFactor = 0.5,
          opacity = 1.0,
          fillOpacity = 0.5,
          fillColor = ~pal2(filtered_data$TM),
          layerId = ~filtered_data$PROVINCIA,                  
          highlightOptions = highlightOptions(color = "white", weight = 2, bringToFront = TRUE),
          label = ~filtered_data$TM,
          labelOptions = labelOptions(
            direction = 'top',
            textOnly = TRUE,
            textsize = "15px",
            style = "font-weight: bold"
          ),
          popup = ~paste("<b>Provincia:</b> ", filtered_data$PROVINCIA, "<br>",
                        "<b>Tasa de Mortalidad c/100 mil hab:</b> ", filtered_data$TM)
        ) %>%
        addLegend(
          position = "topright",
          pal = pal2,
          values = mapa1$TM,
          title = "Tasa de Mortalidad c/100 mil hab"
        )
    })
  }
)