library(readxl)
library(dplyr)
## Warning: package 'dplyr' was built under R version 4.4.3
##
## 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
library(tidyr)
## Warning: package 'tidyr' was built under R version 4.4.3
library(ggplot2)
## Warning: package 'ggplot2' was built under R version 4.4.3
library(forcats)
library(scales)
library(patchwork)
archivo <- "db_tablacomparativa.xlsx"
nombre_hoja <- "Tabla 0 a 100"
# Paleta de colores por entidad
colores_entidades <- c(
"CDMX" = "#061a40",
"Estado de México" = "#0353a4",
"Hidalgo" = "#0077b6",
"Morelos" = "#5b4b9e",
"Puebla" = "#b7a9e0",
"Tlaxcala" = "#9aafd1"
)
datos <- read_excel(
path = archivo,
sheet = nombre_hoja
)
## New names:
## • `` -> `...1`
names(datos)[1] <- "Entidad"
datos <- datos %>%
mutate(
Entidad = recode(
as.character(Entidad),
"CDMX" = "CDMX",
"EDOMEX" = "Estado de México",
"Edomex" = "Estado de México",
"HGO" = "Hidalgo",
"MOR" = "Morelos",
"PUE" = "Puebla",
"TLAX" = "Tlaxcala",
.default = as.character(Entidad)
)
)
columnas_necesarias <- c(
"Entidad",
"Potencial NS",
"Integración",
"Dinamismo económico",
"Especialización productiva",
"Empleo Formal",
"Salarios",
"Capital Humano",
"IED",
"Exportaciones",
"Infraestructura",
"Seguridad",
"Presión hídrica",
"Energía",
"Participación Manufacturera",
"Valor anual de producción manufacturera por persona ocupada",
"Index General"
)
columnas_faltantes <- setdiff(
columnas_necesarias,
names(datos)
)
if (length(columnas_faltantes) > 0) {
stop(
paste0(
"Faltan las siguientes columnas en la hoja:\n",
paste(columnas_faltantes, collapse = "\n")
)
)
}
columnas_numericas <- setdiff(
columnas_necesarias,
"Entidad"
)
datos <- datos %>%
mutate(
across(
all_of(columnas_numericas),
~ as.numeric(.x)
)
)
orden_entidades <- datos %>%
arrange(desc(`Index General`)) %>%
pull(Entidad)
datos <- datos %>%
mutate(
Entidad = factor(
Entidad,
levels = orden_entidades
)
)
limite_indice <- max(
datos$`Index General`,
na.rm = TRUE
) * 1.15
grafica_indice <- ggplot(
datos,
aes(
x = `Index General`,
y = fct_rev(Entidad),
fill = Entidad
)
) +
geom_col(
width = 0.68
) +
geom_text(
aes(
label = number(
`Index General`,
accuracy = 0.1,
decimal.mark = "."
)
),
hjust = -0.15,
size = 4,
color = "black"
) +
scale_fill_manual(
values = colores_entidades,
drop = FALSE
) +
scale_x_continuous(
limits = c(0, limite_indice),
breaks = pretty_breaks(n = 7),
expand = expansion(mult = c(0, 0.01))
) +
labs(
title = "Ranking general de las entidades de la región centro",
subtitle = "Índice compuesto en escala de 0 a 100",
x = "Índice general",
y = NULL,
caption = paste(
"El índice general corresponde al promedio de las dimensiones",
"normalizadas. Véase Anexo metodológico A."
)
) +
theme_minimal(base_size = 12) +
theme(
plot.title = element_text(
face = "bold",
size = 16,
hjust = 0
),
plot.subtitle = element_text(
size = 11,
color = "gray30"
),
axis.title.x = element_text(
face = "bold"
),
axis.text.y = element_text(
face = "bold",
color = "black",
size = 10
),
axis.text.x = element_text(
color = "black"
),
panel.grid.major.y = element_blank(),
panel.grid.minor = element_blank(),
legend.position = "none",
plot.caption = element_text(
hjust = 0,
color = "gray35",
size = 9
),
plot.margin = margin(
t = 10,
r = 25,
b = 10,
l = 10
)
)
print(grafica_indice)
#Heatmap
datos_heatmap <- datos %>%
select(
Entidad,
`Potencial NS`,
Integración,
`Dinamismo económico`,
`Especialización productiva`,
`Empleo Formal`,
Salarios,
`Capital Humano`,
IED,
Exportaciones,
Infraestructura,
Seguridad,
`Presión hídrica`,
Energía,
`Participación Manufacturera`,
`Valor anual de producción manufacturera por persona ocupada`
) %>%
pivot_longer(
cols = -Entidad,
names_to = "Dimension",
values_to = "Puntaje"
)
datos_heatmap <- datos_heatmap %>%
mutate(
Dimension = recode(
Dimension,
"Potencial NS" =
"Potencial de\nnearshoring",
"Integración" =
"Integración a\ncadenas de valor",
"Dinamismo económico" =
"Dinamismo\neconómico",
"Especialización productiva" =
"Especialización\nproductiva",
"Empleo Formal" =
"Empleo\nformal",
"Capital Humano" =
"Capital\nhumano",
"Presión hídrica" =
"Sustentabilidad\nhídrica",
"Participación Manufacturera" =
"Participación\nmanufacturera",
"Valor anual de producción manufacturera por persona ocupada" =
"Producción por\npersona ocupada"
),
Dimension = factor(
Dimension,
levels = c(
"Potencial de\nnearshoring",
"Integración a\ncadenas de valor",
"Dinamismo\neconómico",
"Especialización\nproductiva",
"Empleo\nformal",
"Salarios",
"Capital\nhumano",
"IED",
"Exportaciones",
"Infraestructura",
"Seguridad",
"Sustentabilidad\nhídrica",
"Energía",
"Participación\nmanufacturera",
"Producción por\npersona ocupada"
)
),
## Intesnidad de los colores
color_texto = case_when(
is.na(Puntaje) ~ "black",
Puntaje >= 58 ~ "white",
TRUE ~ "black"
),
etiqueta = if_else(
is.na(Puntaje),
"N/D",
number(
Puntaje,
accuracy = 0.1,
decimal.mark = "."
)
)
)
grafica_heatmap <- ggplot(
datos_heatmap,
aes(
x = Dimension,
y = fct_rev(Entidad),
fill = Puntaje
)
) +
geom_tile(
color = "white",
linewidth = 0.9
) +
geom_text(
aes(
label = etiqueta,
color = color_texto
),
size = 3.1,
fontface = "bold"
) +
scale_color_identity() +
scale_fill_gradientn(
colours = c(
"#f3f4f8",
"#b7a9e0",
"#9aafd1",
"#0077b6",
"#0353a4",
"#061a40"
),
values = rescale(
c(0, 20, 40, 60, 80, 100)
),
limits = c(0, 100),
breaks = c(0, 20, 40, 60, 80, 100),
na.value = "gray85",
name = "Puntaje"
) +
labs(
title = "Comparación estatal por dimensión",
subtitle = paste(
"Puntajes normalizados de 0 a 100;",
"un valor mayor representa un mejor desempeño"
),
x = NULL,
y = NULL,
caption = paste(
"N/D: información no disponible.",
"Las variables de seguridad y presión hídrica fueron invertidas",
"para que un mayor puntaje represente una condición más favorable.",
"Participación manufacturera, \nproducción por trabajador, agua, energía, nearshoring e integración a cadenas de valor son variables proxy. Ver anexo metodológico."
)
) +
theme_minimal(base_size = 11) +
theme(
plot.title = element_text(
face = "bold",
size = 16,
hjust = 0
),
plot.subtitle = element_text(
size = 11,
color = "gray30"
),
axis.text.x = element_text(
angle = 45,
hjust = 1,
vjust = 1,
color = "black",
size = 8.5
),
axis.text.y = element_text(
face = "bold",
color = "black",
size = 10
),
axis.ticks = element_blank(),
panel.grid = element_blank(),
legend.position = "bottom",
legend.title = element_text(
face = "bold"
),
plot.caption = element_text(
hjust = 0,
color = "gray35",
size = 9
),
plot.margin = margin(
t = 10,
r = 10,
b = 10,
l = 10
)
) +
guides(
fill = guide_colorbar(
title.position = "top",
title.hjust = 0.5,
barwidth = unit(11, "cm"),
barheight = unit(0.45, "cm")
)
)
print(grafica_heatmap)
grafica_completa <- grafica_indice /
grafica_heatmap +
plot_layout(
heights = c(1, 2.4)
)
print(grafica_completa)
ggsave(
filename = "01_ranking_indice_general.png",
plot = grafica_indice,
width = 10,
height = 5.8,
dpi = 300,
bg = "white"
)
ggsave(
filename = "02_heatmap_comparativo.png",
plot = grafica_heatmap,
width = 15,
height = 6.8,
dpi = 300,
bg = "white"
)
ggsave(
filename = "03_ranking_y_heatmap.png",
plot = grafica_completa,
width = 15,
height = 11.5,
dpi = 300,
bg = "white"
)