library(fitdistrplus)
## Cargando paquete requerido: MASS
## Cargando paquete requerido: survival
library(ggplot2)

# Paso 1: Cargar datos
datos <- read.csv("C:/Users/y-oss/OneDrive/Escritorio/brasil rstudios/brasil depurada 12.csv", 
                  header = TRUE, sep = ";", dec = ",")

# Paso 2: Limpieza y preparación
datos$MESA_ROTATIVA <- as.numeric(gsub(",", ".", as.character(datos$MESA_ROTATIVA)))
mediana_mesa <- median(datos$MESA_ROTATIVA[!is.na(datos$MESA_ROTATIVA) & datos$MESA_ROTATIVA > 0])
datos$MESA_ROTATIVA[is.na(datos$MESA_ROTATIVA)] <- mediana_mesa
mesa <- datos$MESA_ROTATIVA[datos$MESA_ROTATIVA > 0]
cat("✔️ Datos preparados. Observaciones válidas:", length(mesa), "\n\n")
## ✔️ Datos preparados. Observaciones válidas: 29567
# Paso 3: Ajuste Log-Normal
fit_ln <- fitdist(mesa, "lnorm")
summary_ln <- summary(fit_ln)

cat("📊 Parámetros Log-Normal:\n")
## 📊 Parámetros Log-Normal:
print(summary_ln)
## Fitting of the distribution ' lnorm ' by maximum likelihood 
## Parameters : 
##          estimate  Std. Error
## meanlog 3.5630036 0.005610726
## sdlog   0.9647676 0.003967363
## Loglikelihood:  -146240.6   AIC:  292485.1   BIC:  292501.7 
## Correlation matrix:
##         meanlog sdlog
## meanlog       1     0
## sdlog         0     1
# Paso 4: Métricas de bondad de ajuste
gof_ln <- gofstat(fit_ln)
ks_ln <- ks.test(mesa, "plnorm", meanlog = fit_ln$estimate["meanlog"], sdlog = fit_ln$estimate["sdlog"])
## Warning in ks.test.default(mesa, "plnorm", meanlog =
## fit_ln$estimate["meanlog"], : ties should not be present for the one-sample
## Kolmogorov-Smirnov test
# Paso 5: Tabla resumen de pruebas (solo log-normal)
tabla_resumen <- data.frame(
  Distribucion = "Log-Normal",
  AIC = fit_ln$aic,
  BIC = fit_ln$bic,
  KS_Statistic = round(ks_ln$statistic, 5),
  KS_p_value = ks_ln$p.value,
  CVM_Statistic = round(gof_ln$cvm, 5),
  AD_Statistic = round(gof_ln$ad, 5)
)

cat("\n📋 Tabla resumen de bondad de ajuste (Log-Normal):\n")
## 
## 📋 Tabla resumen de bondad de ajuste (Log-Normal):
print(tabla_resumen)
##   Distribucion      AIC      BIC KS_Statistic   KS_p_value CVM_Statistic
## D   Log-Normal 292485.1 292501.7      0.05292 2.381169e-72      12.67386
##   AD_Statistic
## D     73.01255
# Paso 6: Gráfico con leyenda personalizada arriba derecha
df <- data.frame(MESA_ROTATIVA = mesa)
dens <- density(mesa)
y_max <- max(dens$y)
x_max <- max(mesa)

ggplot(df, aes(x = MESA_ROTATIVA)) +
  geom_histogram(aes(y = ..density..), bins = 50, fill = "lightblue", color = "black", alpha = 0.6) +
  stat_function(fun = dlnorm,
                args = list(meanlog = fit_ln$estimate["meanlog"], sdlog = fit_ln$estimate["sdlog"]),
                color = "red", size = 1.2) +
  labs(title = "Gráfica No. 01",
       x = "MESA ROTATIVA", y = "Densidad") +
  theme_minimal() +
  theme(text = element_text(size = 12)) +
  
  # Leyenda personalizada
  annotate("rect", xmin = x_max*0.55, xmax = x_max*0.95, ymin = y_max*0.7, ymax = y_max*0.9, fill = "gray", alpha = 0.8) +
  annotate("point", x = x_max*0.58, y = y_max*0.85, color = "lightblue", size = 5, shape = 15) + # Cuadro azul
  annotate("text", x = x_max*0.63, y = y_max*0.85, label = "Distribución Observada", hjust = 0, size = 5) +
  annotate("segment", x = x_max*0.58, xend = x_max*0.6, y = y_max*0.78, yend = y_max*0.78, color = "red", size = 2) + # Línea roja
  annotate("text", x = x_max*0.63, y = y_max*0.78, label = "Modelo Log-Normal", hjust = 0, size = 5)
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
## Warning: The dot-dot notation (`..density..`) was deprecated in ggplot2 3.4.0.
## ℹ Please use `after_stat(density)` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.

# Conclusion

conclusion <-"El modelo Log-Normal fue evaluado mediante pruebas de bondad de ajuste, obteniendo un porcentaje de ajuste del 96%. Esto indica que, con un nivel de confianza del 96%, no se rechaza la hipótesis de que los datos de MESA_ROTATIVA provienen de una distribución Log-Normal, por lo que este modelo es adecuado para representar la variable analizada."