Row

Capital

Soacha

Municipios

116

Personas

2792877

Row

Mapa

Pirámide Poblacional

---
title: "Cundinamarca"
output: 
  flexdashboard::flex_dashboard:
    orientation: rows
    social: menu
    source_code: embed
---

```{r setup, include=FALSE}
library(flexdashboard)
library(tidyverse)
library(sf)
library(leaflet)
library(data.table)
library(plotly)

colors <- c("#F5F7F8", "#F4CE14", "#379777", "#45474B")

##### Cargar los datos ####
mapa_mnpios <- st_read('mapas/SHP_MGN2018_INTGRD_MPIO/MGN_ANM_MPIOS.shp') %>%
  st_transform(crs = 4326)  # Transformar a WGS84

cun_mnpios <- mapa_mnpios %>%
  filter(DPTO_CCDGO == 25) %>%
  mutate(MPIO_CNMBR = str_to_title(MPIO_CNMBR))

###### Calcular proporciones ###### 
cun_mnpios <- cun_mnpios %>%
  mutate(
    densidad = STP27_PERS / AREA,
    prop_internet = STP19_INT1 / (STP19_INT1 + STP19_INT2),
    prop_alc = STP19_ALC1 / (STP19_ALC1 + STP19_ALC2),
    prop_acu = STP19_ACU1 / (STP19_ACU1 + STP19_ACU2),
    nivel_educativo = case_when(
      STP51_PRIM > STP51_SECU & STP51_PRIM > STP51_SUPE & STP51_PRIM > STP51_POST ~ "Primaria",
      STP51_SECU > STP51_PRIM & STP51_SECU > STP51_SUPE & STP51_SECU > STP51_POST ~ "Secundaria",
      STP51_SUPE > STP51_PRIM & STP51_SUPE > STP51_SECU & STP51_SUPE > STP51_POST ~ "Superior",
      STP51_POST > STP51_PRIM & STP51_POST > STP51_SECU & STP51_POST > STP51_SUPE ~ "Posgrado",
      TRUE ~ "Indeterminado"
    ),
    grupo_edad = case_when(
      STP34_1_ED == pmax(STP34_1_ED, STP34_2_ED, STP34_3_ED, STP34_4_ED, STP34_5_ED, STP34_6_ED, STP34_7_ED, STP34_8_ED, STP34_9_ED) ~ "0 - 9 años",
      STP34_2_ED == pmax(STP34_1_ED, STP34_2_ED, STP34_3_ED, STP34_4_ED, STP34_5_ED, STP34_6_ED, STP34_7_ED, STP34_8_ED, STP34_9_ED) ~ "10 - 19 años",
      STP34_3_ED == pmax(STP34_1_ED, STP34_2_ED, STP34_3_ED, STP34_4_ED, STP34_5_ED, STP34_6_ED, STP34_7_ED, STP34_8_ED, STP34_9_ED) ~ "20 - 29 años",
      STP34_4_ED == pmax(STP34_1_ED, STP34_2_ED, STP34_3_ED, STP34_4_ED, STP34_5_ED, STP34_6_ED, STP34_7_ED, STP34_8_ED, STP34_9_ED) ~ "30 - 39 años",
      STP34_5_ED == pmax(STP34_1_ED, STP34_2_ED, STP34_3_ED, STP34_4_ED, STP34_5_ED, STP34_6_ED, STP34_7_ED, STP34_8_ED, STP34_9_ED) ~ "40 - 49 años",
      STP34_6_ED == pmax(STP34_1_ED, STP34_2_ED, STP34_3_ED, STP34_4_ED, STP34_5_ED, STP34_6_ED, STP34_7_ED, STP34_8_ED, STP34_9_ED) ~ "50 - 59 años",
      STP34_7_ED == pmax(STP34_1_ED, STP34_2_ED, STP34_3_ED, STP34_4_ED, STP34_5_ED, STP34_6_ED, STP34_7_ED, STP34_8_ED, STP34_9_ED) ~ "60 - 69 años",
      STP34_8_ED == pmax(STP34_1_ED, STP34_2_ED, STP34_3_ED, STP34_4_ED, STP34_5_ED, STP34_6_ED, STP34_7_ED, STP34_8_ED, STP34_9_ED) ~ "70 - 79 años",
      STP34_9_ED == pmax(STP34_1_ED, STP34_2_ED, STP34_3_ED, STP34_4_ED, STP34_5_ED, STP34_6_ED, STP34_7_ED, STP34_8_ED, STP34_9_ED) ~ "80 y más años",
      TRUE ~ "Sin edad asignada"
    ),
    estrato = case_when(
      STP19_EE_1 == pmax(STP19_EE_1, STP19_EE_2, STP19_EE_3, STP19_EE_4, STP19_EE_5, STP19_EE_6) ~ "Estrato 1",
      STP19_EE_2 == pmax(STP19_EE_1, STP19_EE_2, STP19_EE_3, STP19_EE_4, STP19_EE_5, STP19_EE_6) ~ "Estrato 2",
      STP19_EE_3 == pmax(STP19_EE_1, STP19_EE_2, STP19_EE_3, STP19_EE_4, STP19_EE_5, STP19_EE_6) ~ "Estrato 3",
      STP19_EE_4 == pmax(STP19_EE_1, STP19_EE_2, STP19_EE_3, STP19_EE_4, STP19_EE_5, STP19_EE_6) ~ "Estrato 4",
      STP19_EE_5 == pmax(STP19_EE_1, STP19_EE_2, STP19_EE_3, STP19_EE_4, STP19_EE_5, STP19_EE_6) ~ "Estrato 5",
      STP19_EE_6 == pmax(STP19_EE_1, STP19_EE_2, STP19_EE_3, STP19_EE_4, STP19_EE_5, STP19_EE_6) ~ "Estrato 6",
      TRUE ~ "Sin estrato asignado"
    )
  )

```

## Row {data-width="650"}

### Capital

```{r}
# Filtrar el municipio de Soacha usando MPIO_CC = 754
capital <- cun_mnpios %>% filter(MPIO_CCDGO == 754)

valueBox(capital$MPIO_CN, "Capital", icon = "fa-map-marker", color = colors[2])

```

### Municipios

```{r}
# Contar el número de municipios
count_municipios <- nrow(cun_mnpios)

valueBox(count_municipios, "Total Municipios", icon = "fa-building", color = colors[3])

```

### Personas

```{r}

# Sumar el total de personas en STP27_P
total_personas <- sum(cun_mnpios$STP27_PERS)

valueBox(total_personas, "Total Personas", icon = "fa-users", color = colors[4])

```

## Row {data-width="650"}

### Mapa

```{r}
# Mapa interactivo
leaflet(cun_mnpios) %>%
  addProviderTiles(providers$CartoDB.PositronNoLabels) %>%
  addPolygons(
    fillColor = colors[2],  # Color inicial
    weight = 1,  
    opacity = 1,  
    color = "black",  
    fillOpacity = 0.7,  
    label = ~MPIO_CNMBR,  # Mostrar el nombre del municipio
    popup = ~paste(
      "<h2><strong>", MPIO_CNMBR, "</strong></h2>",
      "<table style='width:100%;'>",
      "<tr><td><b>Dens. poblacional:</b></td><td style='text-align:right;'>", format(round(cun_mnpios$densidad, 4), nsmall = 4), "</td></tr>",
      "<tr><td><b>Edad pred:</b></td><td style='text-align:right;'>", cun_mnpios$grupo_edad, "</td></tr>",
      "<tr><td><b>Estrato pred:</b></td><td style='text-align:right;'>", cun_mnpios$estrato, "</td></tr>",
      "<tr><td><b>Nvl educativo:</b></td><td style='text-align:right;'>", cun_mnpios$nivel_educativo, "</td></tr>",
      "<tr><td><b>Internet:</b></td><td style='text-align:right;'>", round(cun_mnpios$prop_internet * 100, 2), "%</td></tr>",
      "<tr><td><b>Acueducto:</b></td><td style='text-align:right;'>", round(cun_mnpios$prop_acu * 100, 2), "%</td></tr>",
      "<tr><td><b>Alcantarillado:</b></td><td style='text-align:right;'>", round(cun_mnpios$prop_alc * 100, 2), "%</td></tr>",
      "</table>"
    ),
    layerId = ~MPIO_CNMBR  # Definir el ID de cada municipio para cambiar su color
  )

```

### Pirámide Poblacional

```{r}
cundinamarca_df <- fread("25_Cundinamarca_CSV/cundinamarca.csv", 
                         colClasses = list(character = c("U_DPTO", "U_MPIO", "UA_CLASE", 
                                                         "UA1_LOCALIDAD", "U_SECT_RUR", 
                                                         "U_SECC_RUR", "UA2_CPOB", 
                                                         "U_SECT_URB", "U_SECC_URB", 
                                                         "U_MZA", "U_EDIFICA", 
                                                         "COD_ENCUESTAS", "U_VIVIENDA", 
                                                         "COD_DANE_ANM")))

#### Funciones ####
# Función para obtener las variables que necesitan codificación
get_variables_to_code <- function() {
  # Leer el archivo del diccionario
  dict_df <- read_delim('./labels/Categorias.csv', 
                        delim = ";", 
                        col_types = "ccic")
  
  # Obtener los valores únicos de CodificacionVariable
  variables_to_code <- unique(dict_df$CodificacionVariable)
  
  return(variables_to_code)
}

# Función para obtener las categorías y descripciones de una variable
get_variable_categories <- function(variable_name) {
  # Leer el archivo del diccionario
  dict_df <- read_delim('./labels/Categorias.csv', 
                        delim = ";", 
                        col_types = "ccic")
  
  # Filtrar las filas de la variable específica
  variable_categories <- dict_df %>%
    filter(CodificacionVariable == variable_name) %>%
    rename(label = Label,
           desc = Descripcion) %>%
    select(label, desc)
  
  return(variable_categories)
}

# Función para poner las descripciones de todas las variables a decodificar
set_variable_categories <- function(df) {
  # Obtener la lista de variables que necesitan codificación
  variables_to_code <- get_variables_to_code()
  
  # Iterar sobre cada variable que necesita codificación
  for (var in variables_to_code) {
    # Verificar si la variable existe en el dataframe
    if (var %in% names(df)) {
      # Obtener las etiquetas y descripciones para la variable actual
      labels <- get_variable_categories(var)
      
      # Reemplazar los códigos en el dataframe con sus descripciones correspondientes
      df[[var]] <- labels$desc[match(df[[var]], labels$label)]
    } else {
      # Si la variable no está en el dataframe, emitir una advertencia
      warning(paste("La variable", var, "no está en el dataframe."))
    }
  }
  
  # Devolver el dataframe modificado
  return(df)
}

cundinamarca_df <- set_variable_categories(cundinamarca_df)

edad_orden <- c(
  "de 00 A 04 Años", "de 05 A 09 Años", "de 10 A 14 Años", "de 15 A 19 Años",
  "de 20 A 24 Años", "de 25 A 29 Años", "de 30 A 34 Años", "de 35 A 39 Años",
  "de 40 A 44 Años", "de 45 A 49 Años", "de 50 A 54 Años", "de 55 A 59 Años",
  "de 60 A 64 Años", "de 65 A 69 Años", "de 70 A 74 Años", "de 75 A 79 Años",
  "de 80 A 84 Años", "de 85 A 89 Años", "de 90 A 94 Años", "de 95 A 99 Años",
  "de 100 y más Años"
)

piramide_data <- cundinamarca_df %>%
  count(P_EDADR, P_SEXO) %>%
  group_by(P_SEXO) %>%
  mutate(
    P_EDADR = factor(P_EDADR, levels = edad_orden),
    percentage = n / sum(n) * 100 * ifelse(P_SEXO == "Hombre", -1, 1)
  ) %>%
  ungroup()

piramide_plot <- ggplot(piramide_data, aes(x = P_EDADR, y = percentage, fill = P_SEXO)) +
  geom_bar(stat = "identity") +
  coord_flip() +
  scale_fill_manual(values = c(colors[3], colors[4])) +
  scale_y_continuous(labels = function(x) paste0(abs(x), "%"),
                     limits = max(abs(piramide_data$percentage)) * c(-1, 1)) +
  labs(x = "Grupo de Edad", y = "Porcentaje", fill = "Género") +
  theme_minimal() +
  theme(legend.position = "bottom",
        axis.text.y = element_text(size = 8))

# Convertir a un gráfico interactivo con plotly
ggplotly(piramide_plot)
```