En este primer paso, preparamos el entorno de trabajo cargando las
librerías necesarias para el análisis de datos (dplyr), la
creación de gráficas avanzadas (ggplot2), y el formato
profesional de tablas (gt).
library(readxl)
library(dplyr)
library(gt)
library(ggplot2)
# Se abre ventana emergente para seleccionar dinámicamente el dataset
ruta_archivo <- file.choose()
datos_originales <- read_excel(ruta_archivo)
cat("Dataset cargado exitosamente. Total de variables:", ncol(datos_originales), "\n")## Dataset cargado exitosamente. Total de variables: 32
Se aísla la variable de interés (Location accuracy) y se
eliminan los registros nulos (NA). Esto garantiza que los
porcentajes reflejen exclusivamente aquellos yacimientos que cuentan con
un nivel de precisión reportado.
tdf_unidades <- datos_originales %>%
select(`Location accuracy`) %>%
filter(!is.na(`Location accuracy`)) %>%
mutate(Categoria = trimws(as.character(`Location accuracy`))) %>%
group_by(Categoria) %>%
summarise(Fi = n()) %>%
arrange(desc(Fi)) %>%
mutate(
hi = Fi / sum(Fi),
Pi = hi * 100,
Fi_ac = cumsum(Fi),
hi_ac = cumsum(hi)
)
N <- sum(tdf_unidades$Fi)
cat("Variable analizada: Location accuracy\n")## Variable analizada: Location accuracy
## Total de observaciones limpias (N): 7538
La tabla estructura las categorías de precisión. Las frecuencias acumuladas permiten evaluar rápidamente qué porcentaje de la base de datos cumple con niveles de precisión específicos o superiores.
# Fila de totales
fila_total <- data.frame(
Categoria = "TOTAL",
Fi = sum(tdf_unidades$Fi),
hi = sum(tdf_unidades$hi),
Pi = sum(tdf_unidades$Pi),
Fi_ac = NA,
hi_ac = NA
)
TDF_Final <- bind_rows(tdf_unidades %>% mutate(Categoria = as.character(Categoria)), fila_total)
fuente_nota <- paste("Fuente: Global Energy Monitor — GOGET 2023 | n =", format(N, big.mark = ","))
TDF_Final %>%
gt() %>%
tab_header(
title = md("**TABLA 1. Distribución de Frecuencias por Precisión de Ubicación**")
) %>%
cols_label(
Categoria = "Nivel de Precisión",
Fi = md("Frec. Absoluta<br>(Fi)"),
hi = md("Frec. Relativa<br>(hi)"),
Pi = md("Porcentaje<br>(%)"),
Fi_ac = md("Frec. Abs.<br>Acumulada (Fi_ac)"),
hi_ac = md("Frec. Rel.<br>Acumulada (hi_ac)")
) %>%
cols_align(align = "center", columns = everything()) %>%
fmt_number(columns = c(hi, hi_ac), decimals = 5) %>%
fmt_number(columns = c(Pi), decimals = 2) %>%
fmt_number(columns = c(Fi, Fi_ac), decimals = 0, use_seps = TRUE) %>%
sub_missing(columns = everything(), missing_text = "") %>%
tab_source_note(fuente_nota) %>%
tab_style(
style = cell_fill(color = "#F5F5F5"),
locations = cells_body(rows = nrow(TDF_Final))
) %>%
tab_style(
style = cell_text(weight = "bold"),
locations = cells_body(rows = nrow(TDF_Final))
) %>%
tab_options(heading.background.color = "#EBF5FB", column_labels.font.weight = "bold")| TABLA 1. Distribución de Frecuencias por Precisión de Ubicación | |||||
| Nivel de Precisión | Frec. Absoluta (Fi) |
Frec. Relativa (hi) |
Porcentaje (%) |
Frec. Abs. Acumulada (Fi_ac) |
Frec. Rel. Acumulada (hi_ac) |
|---|---|---|---|---|---|
| exact | 6,353 | 0.84280 | 84.28 | 6,353 | 0.84280 |
| approximate | 1,185 | 0.15720 | 15.72 | 7,538 | 1.00000 |
| TOTAL | 7,538 | 1.00000 | 100.00 | ||
| Fuente: Global Energy Monitor — GOGET 2023 | n = 7,538 | |||||
# Paleta de colores dinámica ajustada al número de categorías
paleta_azul <- colorRampPalette(c("#08519c", "#3182bd", "#6baed6", "#9ecae1", "#c6dbef"))(nrow(tdf_unidades))ggplot(tdf_unidades, aes(x = reorder(Categoria, -Fi), y = Fi, fill = Categoria)) +
geom_bar(stat = "identity", show.legend = FALSE, color = "black", size = 0.3) +
geom_text(aes(label = format(Fi, big.mark = ",")), vjust = -0.5, size = 3.5, fontface = "bold") +
scale_fill_manual(values = paleta_azul) +
theme_minimal() +
labs(x = "Nivel de Precisión", y = "Frecuencia Absoluta (Fi)") +
theme(
plot.title = element_blank(),
axis.title = element_text(size = 12, face = "bold"),
axis.text = element_text(size = 10),
axis.text.x = element_text(angle = 0, hjust = 0.5)
) +
scale_y_continuous(expand = expansion(mult = c(0, 0.15)))ggplot(tdf_unidades, aes(x = reorder(Categoria, -Pi), y = Pi, fill = Categoria)) +
geom_bar(stat = "identity", show.legend = FALSE, color = "black", size = 0.3) +
geom_text(aes(label = paste0(round(Pi, 1), "%")), vjust = -0.5, size = 3.5, fontface = "bold") +
scale_fill_manual(values = paleta_azul) +
theme_minimal() +
labs(x = "Nivel de Precisión", y = "Porcentaje (%)") +
theme(
plot.title = element_blank(),
axis.title = element_text(size = 12, face = "bold"),
axis.text = element_text(size = 10),
axis.text.x = element_text(angle = 0, hjust = 0.5)
) +
scale_y_continuous(expand = expansion(mult = c(0, 0.15)))# Preparación de etiquetas para leyenda
plot_data <- tdf_unidades %>%
mutate(label_leyenda = paste0(Categoria, " (", round(Pi, 1), "%)"))
ggplot(plot_data, aes(x = "", y = Pi, fill = reorder(label_leyenda, -Pi))) +
geom_bar(stat = "identity", width = 1, color = "white", size = 0.5) +
coord_polar("y", start = 0) +
scale_fill_manual(values = paleta_azul) +
theme_void() +
theme(
legend.position = "right",
legend.text = element_text(size = 11),
legend.title = element_text(face = "bold", size = 12),
plot.margin = margin(t = 20, r = 20, b = 20, l = 20)
) +
guides(fill = guide_legend(title = "Nivel de Precisión"))# Cálculos de indicadores
num_categorias <- nrow(tdf_unidades)
moda_cat <- as.character(tdf_unidades$Categoria[1])
moda_ni <- tdf_unidades$Fi[1]
moda_hi <- round(tdf_unidades$Pi[1], 2)
tabla_ind <- data.frame(
"Total Registros (N)" = format(N, big.mark = ","),
"Niveles Diferentes" = num_categorias,
"Nivel Predominante (Moda)" = moda_cat,
"Frecuencia de la Moda" = format(moda_ni, big.mark = ","),
"Peso de la Moda" = paste0(moda_hi, "%"),
check.names = FALSE
)
tabla_ind %>%
gt() %>%
tab_header(
title = md("**TABLA 2. Indicadores Estadísticos**")
) %>%
cols_align(align = "center", columns = everything()) %>%
tab_source_note("Autor: Grupo 5") %>%
tab_options(heading.background.color = "#EBF5FB", column_labels.font.weight = "bold")| TABLA 2. Indicadores Estadísticos | ||||
| Total Registros (N) | Niveles Diferentes | Nivel Predominante (Moda) | Frecuencia de la Moda | Peso de la Moda |
|---|---|---|---|---|
| 7,538 | 2 | exact | 6,353 | 84.28% |
| Autor: Grupo 5 | ||||