library(dplyr)
library(plotly)
## Cargando paquete requerido: ggplot2
## 
## Adjuntando el paquete: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
Bins_Ready <- Bins 

names(Bins_Ready)[grep("Nombre.*Sucursal", names(Bins_Ready), ignore.case=T)[1]] <- "Nombre Sucursal Origen"
names(Bins_Ready)[grep("Planta|Destino", names(Bins_Ready), ignore.case=T)[1]] <- "Planta"
names(Bins_Ready)[grep("500", names(Bins_Ready))[1]] <- "BINS500"
names(Bins_Ready)[grep("1000", names(Bins_Ready))[1]] <- "BINS1000"
names(Bins_Ready)[grep("Toneladas", names(Bins_Ready), ignore.case=T)[1]] <- "Toneladas"


Datos_Procesados <- Bins_Ready %>%
  mutate(
    
    BINS500 = as.numeric(BINS500),
    BINS1000 = as.numeric(BINS1000),
    
    BINS500 = ifelse(is.na(BINS500), 0, BINS500),
    BINS1000 = ifelse(is.na(BINS1000), 0, BINS1000),
    
    Total_Unidades = BINS500 + BINS1000,
    
    Tipo_Bin = case_when(
      BINS500 > 0 & BINS1000 > 0 ~ "Mixto (500 y 1000)",
      BINS500 > 0 ~ "BINS 500",
      BINS1000 > 0 ~ "BINS 1000",
      TRUE ~ "Otros/Sin Bins"
    )
  ) %>%
  filter(Tipo_Bin != "Otros/Sin Bins")


Resumen_Grafico <- Datos_Procesados %>%
  group_by(Tipo_Bin, `Nombre Sucursal Origen`, Planta) %>%
  summarise(
    Frecuencia = n(),
    Promedio_Unidades = mean(Total_Unidades, na.rm = TRUE), 
    Total_Toneladas = sum(Toneladas, na.rm = TRUE),        
    .groups = 'drop'
  )


grafico <- plot_ly(
  data = Resumen_Grafico,
  x = ~`Nombre Sucursal Origen`,
  y = ~Total_Toneladas,
  type = 'scatter',
  mode = 'markers',
  color = ~Tipo_Bin,
  size = ~Promedio_Unidades, 
  sizes = c(10, 50),
  marker = list(opacity = 0.7, line = list(width = 1, color = 'SlateGrey')),
  text = ~paste(
    "<b>Origen:</b>", `Nombre Sucursal Origen`, "<br>",
    "<b>Destino:</b>", Planta, "<br>",
    "<b>Tipo Bin:</b>", Tipo_Bin, "<br>",
    "<b>Frecuencia (Viajes):</b>", Frecuencia, "<br>",
    "<b>Promedio Unidades:</b>", round(Promedio_Unidades, 1), "<br>",
    "<b>Total Toneladas:</b>", round(Total_Toneladas, 1)
  ),
  hoverinfo = "text"
) %>%
  layout(
    title = "Dinámica de Transporte de Bins (Toneladas vs Origen)",
    xaxis = list(title = "Origen", tickangle = -45),
    yaxis = list(title = "Total Toneladas Transportadas"),
    legend = list(title = list(text = "Tipo de Bin"))
  )


grafico
## Warning: `line.width` does not currently support multiple values.
## Warning: `line.width` does not currently support multiple values.
## Warning: `line.width` does not currently support multiple values.