# Solo la primera vez (quitar el # y correr):
# install.packages(c("gt", "readxl"))
library(gt)
library(readxl)
# =========================
# Cargar Datos
# =========================
datos <- read_excel("Tablas_Frecuencia_Derrame_Petroleo_Grupo5_n543.xlsx", sheet = "Datos")
# Variable original: DEC Region (región administrativa del departamento ambiental DEC)
variable <- paste("Región", datos[["DEC Region"]])
variable[variable == ""] <- NA # celdas vacías = dato faltante
# =========================
# TABLA CUALITATIVA NOMINAL
# =========================
# Conteo: de mayor a menor frecuencia (los empates, por orden alfabético)
tab <- table(variable)
o <- order(-as.vector(tab), names(tab), method = "radix")
categorias <- names(tab)[o]
ni <- as.vector(tab)[o]
# Si hay más de 12 categorías: se conservan las 11 más frecuentes y el resto va en "Otras"
if (length(ni) > 12) {
categorias <- c(categorias[1:11], paste0("Otras (", length(ni) - 11, " categorías)"))
ni <- c(ni[1:11], sum(ni[-(1:11)]))
}
# Registros sin dato (fila aparte, para que el total sea n)
n_faltantes <- sum(is.na(variable))
if (n_faltantes > 0) {
categorias <- c(categorias, "Sin dato (vacío)")
ni <- c(ni, n_faltantes)
}
n <- sum(ni) # tamaño muestral
hi <- ni / n # frecuencia relativa
hp <- hi * 100 # frecuencia relativa (%)
# Máximo y mínimo entre las categorías individuales (sin "Otras" ni "Sin dato")
idx_cat <- which(!grepl("^Otras \\(|^Sin dato", categorias))
i_max <- idx_cat[which.max(ni[idx_cat])]
i_min <- idx_cat[which.min(ni[idx_cat])]
# Fila de totales
TDF <- data.frame(
i = c(seq_along(ni), ""),
xi = c(categorias, "Total"),
ni = c(formatC(ni, format = "d", big.mark = ","), formatC(n, format = "d", big.mark = ",")),
hi = c(formatC(hi, format = "f", digits = 4), formatC(sum(hi), format = "f", digits = 4)),
pct = c(formatC(hp, format = "f", digits = 2), formatC(sum(hp), format = "f", digits = 2))
)
# =========================
# TABLA
# =========================
TDF %>%
gt() %>%
tab_header(
title = md("*Tabla Nro. 1*"),
subtitle = md("**Distribución de derrames por Región DEC, Nueva York**")
) %>%
cols_label(i = "i", xi = html("x<sub>i</sub>"), ni = html("n<sub>i</sub>"),
hi = html("h<sub>i</sub>"), pct = html("h<sub>i</sub> (%)")) %>%
cols_align(align = "center") %>%
tab_style(style = cell_text(weight = "bold"), locations = cells_body(rows = nrow(TDF))) %>%
tab_source_note(
source_note = md("Autor: Grupo 5 \nFuente: Dataset Derrame de Petróleo Grupo 5 (extracto de Spill Incidents, Nueva York; n = 543 derrames)")
) %>%
tab_options(
table.border.top.color = "black",
table.border.bottom.color = "black",
table.border.top.style = "solid",
table.border.bottom.style = "solid",
column_labels.border.top.color = "black",
column_labels.border.bottom.color = "black",
column_labels.border.bottom.width = px(2),
row.striping.include_table_body = TRUE,
heading.border.bottom.color = "black",
heading.border.bottom.width = px(2),
table_body.hlines.color = "gray",
table_body.border.bottom.color = "black"
)
| Tabla Nro. 1 | ||||
| Distribución de derrames por Región DEC, Nueva York | ||||
| i | xi | ni | hi | hi (%) |
|---|---|---|---|---|
| 1 | Región 3 | 270 | 0.4972 | 49.72 |
| 2 | Región 2 | 86 | 0.1584 | 15.84 |
| 3 | Región 8 | 57 | 0.1050 | 10.50 |
| 4 | Región 7 | 44 | 0.0810 | 8.10 |
| 5 | Región 5 | 30 | 0.0552 | 5.52 |
| 6 | Región 4 | 27 | 0.0497 | 4.97 |
| 7 | Región 6 | 10 | 0.0184 | 1.84 |
| 8 | Región 9 | 10 | 0.0184 | 1.84 |
| 9 | Región 1 | 9 | 0.0166 | 1.66 |
| Total | 543 | 1.0000 | 100.00 | |
| Autor: Grupo 5 Fuente: Dataset Derrame de Petróleo Grupo 5 (extracto de Spill Incidents, Nueva York; n = 543 derrames) |
||||
# Colores pastel (uno por categoría), medidas del gráfico y marcas del eje en múltiplos de 5 y 10
colores <- hcl.colors(13, "Pastel 1")[seq_along(ni)]
colores[grepl("^Otras \\(", categorias)] <- "gray80"
colores[categorias == "Sin dato (vacío)"] <- "gray93"
margen_inf <- min(14, 0.5 + max(nchar(categorias)) * 0.38) + 4
pasos <- c(5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 50000)
paso_ni <- pasos[which(max(ni) / pasos <= 10)[1]]
paso_n <- pasos[which(n / pasos <= 10)[1]]
paso_hp <- pasos[which(max(hp) / pasos <= 10)[1]]
# Máximo (borde grueso), mínimo (borde punteado), valores sobre las barras y leyenda
marcar <- function(b, y, etiquetas) {
rect(b[i_max] - 0.5, 0, b[i_max] + 0.5, y[i_max], lwd = 3)
rect(b[i_min] - 0.5, 0, b[i_min] + 0.5, y[i_min], lwd = 3, lty = 2)
text(b, y, labels = etiquetas, pos = 3, cex = 0.8, font = 2, xpd = NA)
legend("topright", legend = c("Máximo (borde grueso)", "Mínimo (borde punteado)"),
lwd = 3, lty = c(1, 2), bty = "n", cex = 0.8, seg.len = 1.5)
}
El máximo es Región 3, con 270 derrames, y el mínimo es Región 1, con 9 derrames.
# =========================================
# Diagrama de barras generado por RStudio
# =========================================
par(mar = c(margen_inf, 6.5, 5, 2))
tope <- ceiling(max(ni) * 1.3 / paso_ni) * paso_ni
b <- barplot(ni,
main = "Gráfica N°1: Distribución de la frecuencia absoluta\nde los derrames por Región DEC",
xlab = "", ylab = "",
col = colores,
ylim = c(0, tope), yaxt = "n",
las = 2,
cex.names = 0.8,
names.arg = categorias)
axis(2, at = seq(0, tope, by = paso_ni), las = 1,
labels = formatC(seq(0, tope, by = paso_ni), format = "d", big.mark = ","))
mtext(expression("Cantidad (" * n[i] * ")"), side = 2, line = 5)
mtext("Categoría", side = 1, line = margen_inf - 1.8)
marcar(b, ni, formatC(ni, format = "d", big.mark = ","))
# ===========================================================
# Diagrama de barras con relación a la totalidad de los datos
# ===========================================================
par(mar = c(margen_inf, 6.5, 5, 2))
b <- barplot(ni,
main = "Gráfica N°2: Distribución general de la frecuencia absoluta\nde los derrames por Región DEC",
xlab = "", ylab = "",
col = colores,
ylim = c(0, n), yaxt = "n",
las = 2,
cex.names = 0.8,
names.arg = categorias)
axis(2, at = seq(0, n, by = paso_n), las = 1,
labels = formatC(seq(0, n, by = paso_n), format = "d", big.mark = ","))
mtext(expression("Cantidad (" * n[i] * ")"), side = 2, line = 5)
mtext("Categoría", side = 1, line = margen_inf - 1.8)
marcar(b, ni, formatC(ni, format = "d", big.mark = ","))
Región 3 representa el 49.72 % de los derrames, y Región 1, el 1.66 %.
# ======================================
# Diagrama de barras que genera RStudio
# ======================================
par(mar = c(margen_inf, 6.5, 5, 2))
tope <- ceiling(max(hp) * 1.3 / paso_hp) * paso_hp
b <- barplot(hp,
main = "Gráfica N°3: Distribución porcentual\nde los derrames por Región DEC",
xlab = "", ylab = "",
col = colores,
ylim = c(0, tope), yaxt = "n",
las = 2,
cex.names = 0.8,
names.arg = categorias)
axis(2, at = seq(0, tope, by = paso_hp), labels = paste0(seq(0, tope, by = paso_hp), "%"), las = 1)
mtext(expression("Porcentaje (" * h[i] * " %)"), side = 2, line = 4)
mtext("Categoría", side = 1, line = margen_inf - 1.8)
marcar(b, hp, paste0(formatC(hp, format = "f", digits = 2), "%"))
# ===========================================================
# Diagrama de barras porcentual con relación a la totalidad
# ===========================================================
par(mar = c(margen_inf, 6.5, 5, 2))
b <- barplot(hp,
main = "Gráfica N°4: Distribución porcentual general\nde los derrames por Región DEC",
xlab = "", ylab = "",
col = colores,
ylim = c(0, 100), yaxt = "n",
las = 2,
cex.names = 0.8,
names.arg = categorias)
axis(2, at = seq(0, 100, by = 10), labels = paste0(seq(0, 100, by = 10), "%"), las = 1)
mtext(expression("Porcentaje (" * h[i] * " %)"), side = 2, line = 4)
mtext("Categoría", side = 1, line = margen_inf - 1.8)
marcar(b, hp, paste0(formatC(hp, format = "f", digits = 2), "%"))
# =========================
# DIAGRAMA CIRCULAR
# =========================
# Punto del borde de cada porción (el ángulo parte de las 12 en punto, en sentido horario)
centro <- 2 * pi * (cumsum(hi) - hi / 2)
xe <- 0.8 * sin(centro)
ye <- 0.8 * cos(centro)
lado <- ifelse(xe >= 0, 1, -1) # 1 = columna derecha, -1 = columna izquierda
# Los porcentajes van en dos columnas rectas, una a cada lado, sin encimarse
ylab <- ye
for (s in c(1, -1)) {
k <- which(lado == s)
if (length(k) == 0) next
k <- k[order(-ye[k])] # de arriba hacia abajo
ylab[k[1]] <- ye[k[1]]
for (m in seq_along(k)[-1]) ylab[k[m]] <- min(ye[k[m]], ylab[k[m - 1]] - 0.12)
bajo <- min(ylab[k]) + 1.05
if (bajo < 0) ylab[k] <- ylab[k] - bajo # si se pasa del borde, sube todo el bloque
}
layout(matrix(1:2, nrow = 1), widths = c(1.6, 1))
par(mar = c(2, 5, 5, 5), xpd = NA)
pie(hi, labels = NA, col = colores, border = "black", lwd = 1.5,
radius = 0.8, clockwise = TRUE,
main = "Gráfica N°5: Distribución porcentual\nde los derrames por Región DEC", cex.main = 1)
segments(xe, ye, lado * 1.00, ylab) # línea desde la porción hasta su columna
segments(lado * 1.00, ylab, lado * 1.06, ylab) # tramo horizontal recto
text(lado * 1.08, ylab, labels = paste0(formatC(hp, format = "f", digits = 2), " %"),
adj = ifelse(lado == 1, 0, 1), cex = 0.9) # porcentajes alineados
par(mar = c(2, 0, 5, 1))
plot.new()
legend("center", legend = categorias, fill = colores, title = "Leyenda", border = "black", bty = "o", cex = 0.85)