library(dplyr)
library(knitr)
library(kableExtra)
library(readxl)
# Cargar datos
Mexico_China <- read_excel("Mexico-China Balanza Comercial.xlsx")
Mexico_China %>%
head(10) %>%
mutate(Año = as.character(Año)) %>% # Evita que se muestre como número con coma
kable("html", caption = "Vista previa de los primeros 10 registros de la base de datos",
align = "c", format.args = list(big.mark = ",")) %>%
kable_styling(full_width = FALSE, bootstrap_options = c("striped", "hover", "condensed", "responsive"))| Año | Exportaciones (USD M) | Importaciones (USD M) | Balanza comercial (USD M) | Tasa de crecimiento Anual Exportaciones | Tasa de crecimiento Anual Importaciones |
|---|---|---|---|---|---|
| 1993 | 44,777,000 | 386,442,000 | -341,665,000 | -0.0584005 | 0.2929625 |
| 1994 | 42,162,000 | 499,655,000 | -457,493,000 | -0.1223851 | 0.0418789 |
| 1995 | 37,002,000 | 520,580,000 | -483,578,000 | 0.0344576 | 0.4593415 |
| 1996 | 38,277,000 | 759,704,000 | -721,427,000 | 0.1986833 | 0.6419237 |
| 1997 | 45,882,000 | 1,247,376,000 | -1,201,494,000 | 1.3097729 | 0.2959156 |
| 1998 | 105,977,000 | 1,616,494,000 | -1,510,517,000 | 0.1921266 | 0.1884096 |
| 1999 | 126,338,000 | 1,921,057,000 | -1,794,719,000 | 0.6114392 | 0.4989769 |
| 2000 | 203,586,000 | 2,879,620,000 | -2,676,034,000 | 0.3840539 | 0.3985363 |
| 2001 | 281,774,000 | 4,027,253,000 | -3,745,479,000 | 1.3207003 | 0.5579803 |
| 2002 | 653,913,000 | 6,274,381,000 | -5,620,468,000 | 0.4900591 | 0.4982499 |
A continuación, se presenta un resumen de los primeros 10 registros de la base de datos que describe la evolución del comercio entre México y China durante las últimas décadas. Esta información incluye los montos anuales de exportaciones e importaciones (en USD), la balanza comercial y las tasas de crecimiento anual tanto de exportaciones como de importaciones.
Estos datos permiten observar las principales tendencias en el intercambio comercial bilateral, destacando períodos de expansión, desequilibrios y cambios en la dinámica económica entre ambos países.
# Instalar si no tienes estas librerías
# install.packages(c("tidyverse", "plotly", "ggthemes", "readxl", "scales"))
library(tidyverse)
library(plotly)
library(ggthemes)
library(readxl)
library(scales)
# Cargar datos
Mexico_China <- read_excel("Mexico-China Balanza Comercial.xlsx") # <- CAMBIA esto por tu ruta local
# Convertir columnas numéricas si están como texto
Mexico_China <- Mexico_China %>%
mutate(across(2:6, as.numeric))
# Crear variables limpias para usar en los gráficos
names(Mexico_China) <- c("Año", "Exportaciones", "Importaciones", "Balanza", "TC_Export", "TC_Import")
# Filtrar solo de 1993 a 2024
Mexico_China <- Mexico_China %>% filter(Año >= 1993 & Año <= 2024)
# =======================
# GRAFICO 1: Exportaciones vs Importaciones (Línea interactiva)
# =======================
p1 <- Mexico_China %>%
pivot_longer(cols = c("Exportaciones", "Importaciones"), names_to = "Tipo", values_to = "Valor") %>%
ggplot(aes(x = Año, y = Valor, color = Tipo)) +
geom_line(size = 1.2) +
geom_point() +
scale_y_continuous(labels = label_dollar(scale = 1e-6, suffix = " M")) +
theme_minimal() +
theme(legend.position = "top") +
labs(title = "Comercio México-China: Exportaciones vs Importaciones",
subtitle = "Valores en millones de USD (1993-2024)",
y = "Valor (USD)", x = "Año", color = "Tipo de Flujo")
ggplotly(p1)Crecimiento sostenido de las importaciones Desde mediados de los años 90, se observa un crecimiento exponencial en las importaciones mexicanas desde China, superando los $100 mil millones de dólares en años recientes. Este comportamiento indica una alta dependencia estructural de México hacia productos de origen chino, posiblemente debido a su competitividad en costos, manufactura y tecnología.
Exportaciones con crecimiento moderado Aunque las exportaciones mexicanas a China también han crecido, su ritmo ha sido mucho más lento y estable, lo cual refleja una relación comercial asimétrica. Incluso en su punto más alto, las exportaciones no superan los $15 mil millones de USD, generando una balanza comercial persistentemente deficitaria para México.
# =======================
# GRAFICO 2: Balanza Comercial
# =======================
p2 <- Mexico_China %>%
ggplot(aes(x = Año, y = Balanza)) +
geom_col(fill = ifelse(Mexico_China$Balanza > 0, "forestgreen", "firebrick")) +
geom_hline(yintercept = 0, linetype = "dashed", color = "black") +
scale_y_continuous(labels = label_dollar(scale = 1e-6, suffix = " M")) +
theme_minimal() +
labs(title = "Balanza Comercial México-China",
subtitle = "Valores negativos indican déficit comercial",
y = "USD", x = "Año")
ggplotly(p2)Déficit comercial persistente y creciente El gráfico muestra que México ha mantenido un déficit comercial constante con China desde 1993, y este déficit ha aumentado drásticamente en magnitud con el paso del tiempo. En los últimos años, el saldo negativo supera los -$100 mil millones de USD, evidenciando una asimetría estructural en los flujos comerciales bilaterales.
Ritmo acelerado de deterioro Desde aproximadamente el año 2010, el déficit crece con una pendiente más pronunciada, lo que indica que el valor de las importaciones ha crecido mucho más rápido que el de las exportaciones. Esta tendencia puede ser el resultado de:
Aumento de la dependencia tecnológica e industrial hacia bienes chinos.
Debilidad en la inserción de productos mexicanos en el mercado chino.
library(dplyr)
library(tidyr)
library(ggplot2)
library(scales)
library(plotly)
# Multiplicar las tasas por 100 para expresarlas en porcentaje
Mexico_China <- Mexico_China %>%
mutate(TC_Export = TC_Export * 100,
TC_Import = TC_Import * 100)
# Filtrar de 1993 a 2024
Mexico_China <- Mexico_China %>% filter(Año >= 1993 & Año <= 2024)
# Crear el gráfico con etiquetas en porcentaje
p3 <- Mexico_China %>%
pivot_longer(cols = c("TC_Export", "TC_Import"),
names_to = "Tipo",
values_to = "Crecimiento") %>%
ggplot(aes(x = Año, y = Crecimiento, color = Tipo)) +
geom_line(size = 1) +
geom_point() +
theme_minimal() +
scale_y_continuous(labels = function(x) paste0(x, "%")) +
labs(title = "Tasa de Crecimiento Anual del Comercio México-China",
subtitle = "Exportaciones e Importaciones (1993-2024)",
y = "Tasa (%)", x = "Año", color = "Indicador")
# Visualizar con plotly (interactivo)
ggplotly(p3)library(tidyverse)
library(plotly)
library(DT)
library(lubridate)
library(reshape2)
library(kableExtra)
library(readxl)
# Cargar los datos
COMPLETO_MEX_CHINA <- read_excel("COMPLETO MEX-CHINA.xlsx")
# Convertir todas las columnas "Trade Value XXXX" a numéricas
COMPLETO_MEX_CHINA <- COMPLETO_MEX_CHINA %>%
mutate(across(starts_with("Trade Value"), ~ as.numeric(.)))
# Transformar de formato ancho a largo
datos_largo <- COMPLETO_MEX_CHINA %>%
select(-starts_with("Share")) %>%
pivot_longer(
cols = starts_with("Trade Value"),
names_to = "Año",
values_to = "Valor_Comercial"
) %>%
mutate(
Año = as.numeric(str_extract(Año, "\\d+")),
Capitulo = `Chapter 4 Digit`,
Sector_HS2 = `HS2 4 Digit`
)
# Calcular participación anual
datos_largo <- datos_largo %>%
group_by(Año) %>%
mutate(Share_Anual = Valor_Comercial / sum(Valor_Comercial, na.rm = TRUE)) %>%
ungroup()
# Evolución del comercio total
evolucion_total <- datos_largo %>%
group_by(Año) %>%
summarise(Valor_Total = sum(Valor_Comercial, na.rm = TRUE))
plot_evolucion <- ggplot(evolucion_total, aes(x = Año, y = Valor_Total)) +
geom_line(color = "#2c3e50", size = 1.5) +
geom_point(color = "#e74c3c", size = 3) +
labs(title = "Evolución Exportaciones Total México-China",
y = "Valor Comercial (USD)",
x = "Año") +
theme_minimal() +
scale_y_continuous(labels = scales::dollar_format()) +
theme(plot.title = element_text(face = "bold", size = 14))
ggplotly(plot_evolucion) %>%
layout(hoverlabel = list(bgcolor = "white"))# 2. Evolución de los 5 principales sectores (2014-2023) ----
top_5_sectores <- datos_largo %>%
filter(Año == 2023) %>% # Usar 2023 como referencia para identificar principales
group_by(Capitulo) %>%
summarise(Valor_Total = sum(Valor_Comercial, na.rm = TRUE)) %>%
top_n(5, Valor_Total) %>%
pull(Capitulo)
plot_top_evolucion <- datos_largo %>%
filter(Capitulo %in% top_5_sectores, Año <= 2023) %>%
group_by(Capitulo, Año) %>%
summarise(Valor_Total = sum(Valor_Comercial, na.rm = TRUE)) %>%
ggplot(aes(x = Año, y = Valor_Total, color = Capitulo, group = Capitulo)) +
geom_line(size = 1.2) +
geom_point(size = 2) +
labs(title = "Evolución de los 5 Principales Sectores (2014-2023)",
y = "Valor Comercial (USD)",
x = "Año",
color = "Sector") +
theme_minimal() +
scale_y_continuous(labels = scales::dollar_format()) +
scale_x_continuous(breaks = seq(2014, 2023, 1)) +
scale_color_brewer(palette = "Set1") +
theme(axis.text.x = element_text(angle = 45, hjust = 1))
ggplotly(plot_top_evolucion) %>%
layout(xaxis = list(tickvals = seq(2014, 2023, 1)))# 7. Heatmap de participación por sector y año ----
heatmap_data <- datos_largo %>%
group_by(Capitulo, Año) %>%
summarise(Share = sum(Share_Anual, na.rm = TRUE)) %>%
filter(Share > 0.01) # Solo sectores con más del 1% de participación
plot_heatmap <- ggplot(heatmap_data, aes(x = Año, y = reorder(Capitulo, Share), fill = Share)) +
geom_tile() +
scale_fill_gradient(low = "white", high = "#e74c3c", labels = scales::percent_format()) +
labs(title = "Evolución de Participación por Sector",
y = "Sector",
x = "Año",
fill = "Participación") +
theme_minimal() +
theme(axis.text.y = element_text(size = 8))
ggplotly(plot_heatmap)# Cargar librerías necesarias
library(tidyverse)
library(plotly)
library(DT)
library(lubridate)
library(reshape2)
library(kableExtra)
library(readxl)
# 1. Cargar datos específicos de IMPORTACIONES desde Excel
COMPLETO_MEX_CHINA2 <- read_excel("COMPLETO MEX-CHINA.xlsx",
sheet = "Importaciones Mex-China")
# Convertir columnas Trade Value a numérico
COMPLETO_MEX_CHINA2 <- COMPLETO_MEX_CHINA2 %>%
mutate(across(starts_with("Trade Value"), ~ as.numeric(.))) %>%
mutate(across(starts_with("Share"), ~ as.numeric(.))) # <--- Agregado
# 2. Preparación de datos para IMPORTACIONES
datos_largo_import <- COMPLETO_MEX_CHINA2 %>%
select(-starts_with("Share")) %>%
pivot_longer(
cols = starts_with("Trade Value"),
names_to = "Año",
values_to = "Valor_Comercial"
) %>%
mutate(
Año = as.numeric(str_extract(Año, "\\d+")),
Capitulo = `Chapter 4 Digit`,
Sector_HS2 = `HS2 4 Digit`
)
# Calcular shares anuales para IMPORTACIONES
datos_largo_import <- datos_largo_import %>%
left_join(
COMPLETO_MEX_CHINA2 %>%
select(`Chapter 4 Digit`, contains("Share")) %>%
pivot_longer(
cols = -`Chapter 4 Digit`,
names_to = "Año_share",
values_to = "Share_Original"
) %>%
mutate(Año = as.numeric(str_extract(Año_share, "\\d+"))),
by = c("Capitulo" = "Chapter 4 Digit", "Año")
)
# 3. Análisis de tendencias generales de IMPORTACIONES
evolucion_import_total <- datos_largo_import %>%
group_by(Año) %>%
summarise(Valor_Total = sum(Valor_Comercial, na.rm = TRUE))
plot_evolucion_import <- ggplot(evolucion_import_total, aes(x = Año, y = Valor_Total)) +
geom_line(color = "#2c3e50", size = 1.5) +
geom_point(color = "#e74c3c", size = 3) +
labs(title = "Evolución de Importaciones Totales México-China",
y = "Valor de Importación (USD)",
x = "Año") +
theme_minimal() +
scale_y_continuous(labels = scales::dollar_format()) +
scale_x_continuous(breaks = seq(min(evolucion_import_total$Año, na.rm = TRUE),
max(evolucion_import_total$Año, na.rm = TRUE), by = 1)) +
theme(plot.title = element_text(face = "bold", size = 14),
axis.text.x = element_text(angle = 45, hjust = 1))
ggplotly(plot_evolucion_import) %>%
layout(hoverlabel = list(bgcolor = "white"))COMPLETO_MEX_CHINA2 <- read_excel("COMPLETO MEX-CHINA.xlsx",
sheet = "Importaciones Mex-China") %>%
mutate(across(starts_with("Trade Value"), ~ as.numeric(.))) %>%
mutate(across(starts_with("Share"), ~ as.numeric(.))) # <- Conversión clave
# 2. Preparar datos en formato largo
datos_largo_import <- COMPLETO_MEX_CHINA2 %>%
select(-starts_with("Share")) %>%
pivot_longer(
cols = starts_with("Trade Value"),
names_to = "Año",
values_to = "Valor_Comercial"
) %>%
mutate(
Año = as.numeric(str_extract(Año, "\\d+")),
Capitulo = `Chapter 4 Digit`
) %>%
filter(Año <= 2023)
# 3. Calcular shares anuales (CORRECCIÓN: usando los shares originales)
datos_largo_import <- datos_largo_import %>%
left_join(
COMPLETO_MEX_CHINA2 %>%
select(`Chapter 4 Digit`, contains("Share")) %>%
pivot_longer(
cols = -`Chapter 4 Digit`,
names_to = "Año_share",
values_to = "Share_Original"
) %>%
mutate(Año = as.numeric(str_extract(Año_share, "\\d+"))),
by = c("Capitulo" = "Chapter 4 Digit", "Año")
)
# 4. Identificar top 5 sectores en 2023
top_5_sectores_import <- datos_largo_import %>%
filter(Año == 2023) %>%
group_by(Capitulo) %>%
summarise(Valor_Total = sum(Valor_Comercial, na.rm = TRUE)) %>%
top_n(5, Valor_Total) %>%
pull(Capitulo)
# 5. Gráfico de evolución
plot_top_evolucion_import <- datos_largo_import %>%
filter(Capitulo %in% top_5_sectores_import) %>%
group_by(Capitulo, Año) %>%
summarise(
Valor_Total = sum(Valor_Comercial, na.rm = TRUE),
Share_Promedio = mean(Share_Original, na.rm = TRUE),
.groups = 'drop'
) %>%
ggplot(aes(x = Año, y = Valor_Total, color = Capitulo)) +
geom_line(size = 1) +
geom_point(size = 2) +
labs(title = "Top 5 Sectores de Importación México-China (2014-2023)",
y = "Valor (USD)",
x = "Año") +
scale_y_continuous(labels = scales::dollar_format()) +
scale_x_continuous(breaks = seq(2014, 2023, 1)) +
theme_minimal()
ggplotly(plot_top_evolucion_import)Máquinas lideran, representando ~50% del total.
Productos Químicos mantienen crecimiento constante.
Transporte (vehículos/autopartes) muestra mayor dinamismo.
Textiles y Rieles con participación menor pero estable.
# Cargar datos específicos de IMPORTACIONES desde Excel
# Convertir columnas 'Trade Value XXXX' a numérico (para evitar errores en pivot_longer)
COMPLETO_MEX_CHINA2 <- COMPLETO_MEX_CHINA2 %>%
mutate(across(starts_with("Trade Value"), ~ as.numeric(.)))
# Preparar datos en formato largo para IMPORTACIONES
datos_largo_import <- COMPLETO_MEX_CHINA2 %>%
select(-starts_with("Share")) %>%
pivot_longer(
cols = starts_with("Trade Value"),
names_to = "Año",
values_to = "Valor_Comercial"
) %>%
mutate(
Año = as.numeric(str_extract(Año, "\\d+")),
Capitulo = `Chapter 4 Digit`,
Sector_HS2 = `HS2 4 Digit`
) %>%
filter(Año <= 2023) # Excluir 2024 si es necesario
# Calcular shares anuales para IMPORTACIONES
datos_largo_import <- datos_largo_import %>%
group_by(Año) %>%
mutate(Share_Anual = Valor_Comercial / sum(Valor_Comercial, na.rm = TRUE)) %>%
ungroup()
# 7. Heatmap de participación por sector y año para IMPORTACIONES ----
heatmap_import_data <- datos_largo_import %>%
group_by(Capitulo, Año) %>%
summarise(Share = sum(Share_Anual, na.rm = TRUE)) %>%
filter(Share > 0.01) # Solo sectores con más del 1% de participación
plot_heatmap_import <- ggplot(heatmap_import_data,
aes(x = Año,
y = reorder(Capitulo, Share),
fill = Share,
text = paste("Sector:", Capitulo,
"<br>Año:", Año,
"<br>Participación:", scales::percent(Share, accuracy = 0.1)))) +
geom_tile(color = "white", linewidth = 0.3) +
scale_fill_gradient(low = "white",
high = "#e74c3c",
labels = scales::percent_format(),
name = "Participación") +
labs(title = "Participación de Sectores en IMPORTACIONES México-China (2014-2023)",
subtitle = "Sectores con >1% participación anual",
y = "Sector",
x = "Año") +
theme_minimal(base_size = 12) +
theme(
axis.text.y = element_text(size = 8),
axis.text.x = element_text(angle = 45, hjust = 1),
plot.title = element_text(face = "bold", color = "#2c3e50"),
plot.subtitle = element_text(color = "#7f8c8d"),
panel.grid = element_blank()
) +
scale_x_continuous(breaks = seq(2014, 2023, 1))
# Versión interactiva con Plotly
ggplotly(plot_heatmap_import, tooltip = "text") %>%
layout(
margin = list(l = 100, r = 50), # Ajustar márgenes para etiquetas
xaxis = list(tickangle = -45),
title = list(text = paste0("Participación de Importaciones México-China (2014-2023)"))
)Máquinas acaparan ≈60% del total (equipos industriales/tecnológicos).
Vulnerabilidad mexicana en cadenas industriales clave.
Oportunidad para desarrollar proveedores locales para sectores estratégicos (plásticos, químicos).
Gráfico sugiere necesidad de política industrial para reducir concentración en 3 sectores (Maquinas,Rieles,Transporte).