library(dplyr)
library(knitr)
library(kableExtra)
library(readxl)
# Cargar datos
Mexico_China <- read_excel("Mexico-Rusia 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 |
|---|---|---|---|---|---|
| 2006 | 42,745,617 | 534,369,239 | -491,623,622 | 2.7228129 | -0.1613373 |
| 2007 | 159,133,936 | 448,155,557 | -289,021,621 | -0.2723192 | 0.8318142 |
| 2008 | 115,798,707 | 820,937,714 | -705,139,007 | -0.6631772 | -0.4296456 |
| 2009 | 39,003,649 | 468,225,454 | -429,221,805 | 5.0789283 | 0.8216525 |
| 2010 | 237,100,384 | 852,944,056 | -615,843,672 | 0.9859805 | 0.3461564 |
| 2011 | 470,876,743 | 1,148,196,095 | -677,319,352 | 0.0421228 | 0.0521568 |
| 2012 | 490,711,409 | 1,208,082,314 | -717,370,905 | -0.0372353 | -0.0180491 |
| 2013 | 472,439,605 | 1,186,277,506 | -713,837,901 | -0.4204710 | 0.2712527 |
| 2014 | 273,792,432 | 1,508,058,473 | -1,234,266,041 | -0.2696574 | -0.0408825 |
| 2015 | 199,962,273 | 1,446,405,306 | -1,246,443,033 | -0.1087261 | -0.1442900 |
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 Rusia durante las últimas décadas. Esta información incluye los montos anuales de exportaciones e importaciones (en USD millones), 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-Rusia 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-Rusia: Exportaciones vs Importaciones",
subtitle = "Valores en millones de USD (2006-2024)",
y = "Valor (USD)", x = "Año", color = "Tipo de Flujo")
ggplotly(p1)# =======================
# 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-Rusia",
subtitle = "Valores negativos indican déficit comercial",
y = "USD", x = "Año")
ggplotly(p2)El gráfico evidencia que México ha mantenido una balanza comercial deficitaria con Rusia durante todo el periodo observado. En ningún año se alcanza un superávit ni siquiera un equilibrio comercial. Desde 2010, el déficit anual se sitúa consistentemente por debajo de los -$500 millones de USD, profundizándose hasta superar los -$2,000 millones de USD en años recientes (especialmente 2021-2023). Esta dinámica refleja una asimetría estructural en el comercio bilateral, donde México importa mucho más de lo que exporta a Rusia.
Deterioro acelerado en años recientes:
A partir de 2018, se observa una aceleración en el crecimiento del déficit comercial, destacando los años 2021 y 2022 como los de mayor desequilibrio. Este deterioro puede atribuirse a:
Incremento de las importaciones mexicanas desde Rusia, probablemente por productos energéticos, fertilizantes u otros bienes estratégicos.
Caída significativa de las exportaciones mexicanas, posiblemente por factores geopolíticos y restricciones derivadas del conflicto Rusia–Ucrania.
Poca diversificación de la oferta exportable de México hacia Rusia, lo cual limita la capacidad de contrarrestar el crecimiento de las importaciones.
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 >= 2006 & Año <= 2023)
# 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-Rusia",
subtitle = "Exportaciones e Importaciones (2006-2023)",
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-Rusia.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-Rusia",
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"))La relación comercial México–Rusia muestra un deterioro significativo, con una caída constante en las exportaciones desde 2021, lo que refleja una pérdida de relevancia del mercado ruso para México en términos de ventas externas.
# 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-Rusia.xlsx",
sheet = "Importaciones_Mex-Rusia")
# 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-Rusia",
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-Rusia.xlsx",
sheet = "Importaciones_Mex-Rusia") %>%
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-Rusia (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)# 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-Rusia (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-Rusia (2014-2023)"))
)Rieles y Químicos dominan las importaciones desde Rusia, concentrando hasta el 60% del total, revelando una alta dependencia sectorial.
Máquinas, Plásticos y Vegetales muestran participación marginal, sin consolidarse como sectores clave en la relación comercial.
Oportunidad para México: fomentar sustitución de importaciones en químicos y rieles mediante política industrial e inversión tecnológica.