###### Universidad Central del Ecuador######
###### Carrera de Petróleos  #####


library(readxl)
library(dplyr)
## 
## Adjuntando el paquete: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(ggplot2)
library(readr)

# Cargar datos
datasetf <- read_csv("datasetf.csv")
## Warning: One or more parsing issues, call `problems()` on your data frame for details,
## e.g.:
##   dat <- vroom(...)
##   problems(dat)
## Rows: 2795 Columns: 36
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (18): Accident Date/Time, Operator Name, Pipeline/Facility Name, Pipelin...
## dbl (18): Report Number, Supplemental Number, Accident Year, Operator ID, Ac...
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
View(datasetf)

# Agrupar por Tipo de Líquido 
Tabla <- datasetf %>%
  count(Liquid_Type = `Liquid Type`, name = "ni") %>%
  arrange(desc(ni))

# TDFfrecuencias
Tabla$hi <- Tabla$ni / sum(Tabla$ni)
Tabla$hi_porcentaje <- round(Tabla$hi * 100, 3)

# Agregar TOTAL
total_fila <- data.frame(
  Liquid_Type = "TOTAL",
  ni = sum(Tabla$ni),
  hi = 1,
  hi_porcentaje = 100.000
)

Tabla_completa <- rbind(Tabla, total_fila)
Tabla_final <- Tabla_completa[, c("Liquid_Type", "ni", "hi_porcentaje")]
names(Tabla_final)[names(Tabla_final) == "hi_porcentaje"] <- "hi"#CAMBIO DE NOMBRE 

# NOMBRES CORTOS PARA MEJOR VISUALIZACIÓN
nombres_cortos <- c(
  "HVL OR OTHER FLAMMABLE OR TOXIC FLUID, GAS" = "HVL GAS",
  "CRUDE OIL" = "CRUDE OIL",
  "REFINED AND/OR PETROLEUM PRODUCT (NON-HVL), LIQUID" = "PETROLEUM",
  "CO2 (CARBON DIOXIDE)" = "CO2",
  "BIOFUEL / ALTERNATIVE FUEL(INCLUDING ETHANOL BLENDS)" = "BIOFUEL"
)

# Aplicar nombres cortos
datos_grafica <- Tabla_final[Tabla_final$Liquid_Type != "TOTAL", ]
datos_grafica$Liquid_Type_short <- nombres_cortos[datos_grafica$Liquid_Type]

View(Tabla_final)
print(Tabla_final)
## # A tibble: 6 × 3
##   Liquid_Type                                             ni      hi
##   <chr>                                                <int>   <dbl>
## 1 CRUDE OIL                                             1398  50.0  
## 2 REFINED AND/OR PETROLEUM PRODUCT (NON-HVL), LIQUID     939  33.6  
## 3 HVL OR OTHER FLAMMABLE OR TOXIC FLUID, GAS             418  15.0  
## 4 CO2 (CARBON DIOXIDE)                                    38   1.36 
## 5 BIOFUEL / ALTERNATIVE FUEL(INCLUDING ETHANOL BLENDS)     2   0.072
## 6 TOTAL                                                 2795 100
# GRÁFICA 1: Barras para ni
barplot(datos_grafica$ni, 
        names.arg = datos_grafica$Liquid_Type_short,
        col = "#4ECDC4",
        main = "Gráfica No.1: 
        Distribución de Pipeline/Facility Name por Tipo de Líquido",
        ylab = "Cantidad",
        las = 2,  
        cex.names = 0.8,
        ylim = c(0, max(datos_grafica$ni) * 1.1))

# GRÁFICA 2: Barras para hi 
barplot(datos_grafica$hi, 
        names.arg = datos_grafica$Liquid_Type_short,
        col = "#4ECDC4",
        main = "Gráfica No.2:
        Distribución de Pipeline/Facility Name por Tipo de Líquido",
        ylab = "Cantidad",
        las = 2,
        cex.names = 0.8,
        ylim = c(0, max(datos_grafica$hi) * 1.1))

# GRÁFICA 3: Barras para (hi * 100) 
barplot(datos_grafica$hi * 100, 
        names.arg = datos_grafica$Liquid_Type_short,
        col = "#4ECDC4", 
        main = "Gráfica Nº3: 
        Distribuciónde Pipeline/Facility Name por Tipo de Líquido", 
        las = 2, 
        cex.names = 0.8,
        ylab = "Cantidad")

# GRÁFICA 4: Pastel 
par(mar = c(2, 2, 2, 15))  
azules_degradado <- c("#1f77b4", "#279ece", "#4fb4d8", "#7bcde8", "#a6e3f7", "#d4f1f9")

pie(datos_grafica$hi * 100,
    labels = NA,  
    col = azules_degradado,
    main ="                       Gráfica Nº3: 
                             Distribuciónde Pipeline Name por Tipo de Líquido",
    cex = 0.10,  # Texto más grande
    radius = 1)

legend(x = 1.5, y = 1,  
       legend = paste0(datos_grafica$Liquid_Type_short, " - ",
                       round(datos_grafica$hi * 100, 1), "%",
                       " (", datos_grafica$ni, " casos)"),
       fill = azules_degradado,
       bty = "t",        
       cex = 0.7,        
       xpd = TRUE)