POLITÉCNICO DE LA COSTA ATLÁNTICA

Graficos Descriptivos

true
Octubre 25, 2022

BASE #1: CONSUMO DE REPROCESO DE DETERGENTE

library(stats)
library(dplyr)
library(readxl)
library(cowplot)
library(ggplot2)
library(viridis)     # Para paletas de colores
library(hrbrthemes)  # Temas, componentes de tema y utilidades adicionales para ggplot2
library(tidyverse)                
library(knitr)
library(patchwork)
library(forecast)
library(TSstudio)
library(lubridate)
library(datasets)
library(plotly)

Se carga la base de datos

datos2<-read_excel("Data2.xlsx")

Grafico 1: Distribución según Lugar de consumo.

#Transformación de los datos para grafica #1
Tabla_1<-datos2 %>% 
  group_by(LUGAR) %>% # Variable a ser transformada
  count() %>% 
  ungroup() %>% 
  mutate(PORCENTAJES = `n` / sum(`n`)) %>% 
  arrange(PORCENTAJES) %>%
  mutate(etiquetas = scales::percent(PORCENTAJES))

#Grafico #1
G1<-ggplot(Tabla_1, aes(x = "", y = PORCENTAJES, fill = LUGAR)) +
  geom_col(color = "black") +
  geom_label(aes(label = etiquetas),
             position = position_stack(vjust = 0.5),
             show.legend = FALSE) +
  guides(fill = guide_legend(title = "LUGAR")) + scale_color_viridis_c() +
  coord_polar(theta = "y") + ggtitle ("DISTRIBUCIÓN SEGÚN SU LUGAR DE CONSUMO")
#theme_void() 
G1

Grafico 2: DESCRIPCIÓN DEL GRANEL

#cargamos las librerias correspondientes
library(tm)
library(NLP)
library(SnowballC)
library(RColorBrewer)
library(wordcloud)
#Que palabras hay con mayor frecuencia en los comentarios para .....
#nuestro texto lo guardamos en bloc de notas en formato txt
texto <- readLines("DESCRIPCION.txt")
texto = iconv(texto, to="ASCII//TRANSLIT")
texto = Corpus(VectorSource(texto)) 
########### LIMPIAMOS NUESTRO TEXTO CON EL COMANDO tm_map
#ponemos todos los datos a minuscula (A!=a)
discurso=tm_map(texto, tolower)
#quitamos los espacios en blanco
discurso =tm_map(discurso, stripWhitespace)
#quitamos la puntuacion
discurso = tm_map(discurso, removePunctuation)
#quitamos los numeros
discurso = tm_map(discurso, removeNumbers)
#mostramos palabras vacias y genericas
#stopwords("spanish")
#quitamos palabras genericas
discurso=tm_map(discurso, removeWords,stopwords("spanish"))
#tambien podemos tener nuestra propia lista de palabras a quitar
############### DATA FRAME DE PALABRAS CON SU FRECUENCIA
#Creamos matriz de letras
letras= TermDocumentMatrix(discurso)
findFreqTerms(letras, lowfreq=5)
 [1] "azul"        "estandar"    "floral"      "maxi"       
 [5] "bicarbonato" "economico"   "enzimatico"  "limon"      
 [9] "verbena"     "blanco"      "super"       "verde"      
[13] "preten"      "premium"     "ptos"        "rosados"    
[17] "plus"        "lavanda"     "det"         "est"        
[21] "flo"         "granel"      "bla"         "pre"        
[25] "naranja"     "member"      "selection"   "pot"        
[29] "den"         "deter"       "eco"         "antib"      
[33] "lim"         "aloe"        "alg"         "ver"        
[37] "act"         "activos"     "oxigenos"    "economio"   
[41] "rosadas"     "exp"        
matrix=as.matrix(letras)
#lo ordenamos y sumamos las letras de nuestra matriz
vector <- sort(rowSums(matrix),decreasing=TRUE) 
#creamos la data con las palabras y su frecuencia
dataletras <- data.frame(word= names(vector),frequencia=vector) 
# lo nombra y le da formato de data.frame
############ GRAFICAMOS LA NUBE DE PALABRAS
#wordcloud(words = dataletras$word, freq = dataletras$freq, min.freq = 1,
         # max.words=100000)
#en el centro la palabra mas importante, 
wordcloud(words = dataletras$word, freq = dataletras$freq, min.freq = 1,
          max.words=100000, random.order=FALSE, rot.per=0.2,
          colors=brewer.pal(8, "Set1"))

Grafico 3: Distribución según los Turnos

"Creación de tabla de frecuencia para hacer el grafico con fr y porcentaje"
[1] "Creación de tabla de frecuencia para hacer el grafico con fr y porcentaje"
Tabla_2 <- datos2 %>%
  dplyr::group_by(TURNO) %>%                                  
  dplyr::summarise(Total = n()) %>%                                
  dplyr::mutate(Porcentaje = round(Total/sum(Total)*100, 1)) %>%   
  dplyr::arrange(TURNO)

"Grafico"
[1] "Grafico"
G3<-ggplot(Tabla_2, aes(x =TURNO, y=Total) ) + 
  geom_bar(width = 0.9,stat="identity",                 
           position = position_dodge(), fill="red3") +  
  ylim(c(0,1100))+
  #xlim(c(0,300)) +                  
  #ggtitle("Un título") + 
  labs(x="TURNO", y= "Frecuencias \n (Porcentajes)")   +   
  geom_text(aes(label=paste0(Total," ", "", "(", Porcentaje, "%", ")")),  
            vjust=-0.9, 
            color="black", 
            hjust=0.5,
            # define text position and size
            position = position_dodge(0.9),  
            angle=0, 
            size=4.0) +   
  theme(axis.text.x = element_text(angle = 0, vjust = 1, hjust=1)) +      
  theme_bw(base_size = 14) +
  #coord_flip() +                                                         
  facet_wrap(~"DISTRIBUCIÓN SEGÚN EL TURNO")
G3

Grafico 4: Distribución según el Motivo

"Creación de tabla de cruzada para hacer el grafico con fr y porcentaje"
[1] "Creación de tabla de cruzada para hacer el grafico con fr y porcentaje"
Tabla_3 <- datos2 %>%
  dplyr::group_by(Motivo) %>%                                  
  dplyr::summarise(Total = n()) %>%                                
  dplyr::mutate(Porcentaje = round(Total/sum(Total)*100, 1)) %>%   
  dplyr::arrange(Motivo)

"Grafico"
[1] "Grafico"
G4<-ggplot(Tabla_3, aes(x =Motivo, y=Total) ) + 
  geom_bar(width = 0.9,stat="identity",                 
           position = position_dodge(), fill="yellow3") +  
  ylim(c(0,1850))+
  #xlim(c(0,300)) +                  
  #ggtitle("Un título") + 
  labs(x="MOTIVO", y= "Frecuencias \n (Porcentajes)")   +   
  geom_text(aes(label=paste0(Total," ", "", "(", Porcentaje, "%", ")")),  
            vjust=-0.9, 
            color="black", 
            hjust=0.5,
            # define text position and size
            position = position_dodge(0.9),  
            angle=0, 
            size=5.0) +   
  theme(axis.text.x = element_text(angle = 0, vjust = 1, hjust=1)) +      
  theme_bw(base_size = 14) +
  #coord_flip() +                                                         
  facet_wrap(~"DISTRIBUCIÓN SEGÚN EL MOTIVO")
G4

Grafico 5: Distribución del Motivo segun Lugar de Consumo

"Creación de Tabla Cruzada"
[1] "Creación de Tabla Cruzada"
Tabla4 <- datos2 %>%
  dplyr::group_by(Motivo, LUGAR) %>%                                  
  dplyr::summarise(Total = n()) %>%                                
  dplyr::mutate(Porcentaje = round(Total/sum(Total)*100, 1)) %>%   
  dplyr::arrange(Motivo)

"Grafico"
[1] "Grafico"
G5<-ggplot(Tabla4, aes(x = Motivo, y=Total, fill=LUGAR) ) + 
  geom_bar(width = 0.9,stat="identity",                 
           position = position_dodge()) +  
  ylim(c(0,80))+
  #xlim(c(0,300)) +                  
  #ggtitle("Un título") + 
  labs(x="", y= "Frecuencias \n (Porcentajes)") +   
  labs(fill = "LUGAR") +                                 
  scale_fill_manual(values = c("pink",  "skyblue")) +   
  geom_text(aes(label=paste0(Total," ", "", "(", Porcentaje, "%", ")")),  
            vjust=-0.9, 
            color="black", 
            hjust=-0.5,
            # define text position and size
            position = position_dodge(0.9),  
            angle=0, 
            size=6.0)+
  scale_fill_discrete(name = "LUGAR", labels = c("PREPARADOR ", "TK DISOLUCION")) +   
  theme(axis.text.x = element_text(angle = 0, vjust = 1, hjust=1)) +      
  theme_bw(base_size = 14) +
  coord_flip() +                                                         
  facet_wrap(~"DISTRIBUCIÓN DEL MOTIVO SEGÚN EL LUGAR DE CONSUMO")
G5

Grafico 6: Distribución del Turno según el Lugar de Consumo

"Creación de Tabla Cruzada"
[1] "Creación de Tabla Cruzada"
Tabla5 <- datos2 %>%
  dplyr::group_by(TURNO, LUGAR) %>%                                  
  dplyr::summarise(Total = n()) %>%                                
  dplyr::mutate(Porcentaje = round(Total/sum(Total)*100, 1)) %>%   
  dplyr::arrange(TURNO)

"Grafico"
[1] "Grafico"
G6<-ggplot(Tabla5, aes(x = TURNO, y=Total, fill=LUGAR) ) + 
  geom_bar(width = 0.9,stat="identity",                 
           position = position_dodge()) +  
  ylim(c(0,1010))+
  #xlim(c(0,300)) +                  
  #ggtitle("Un título") + 
  labs(x="", y= "Frecuencias \n (Porcentajes)") +   
  labs(fill = "Sexo") +                                 
  scale_fill_manual(values = c("cyan",  "red2")) +   
  geom_text(aes(label=paste0(Total," ", "", "(", Porcentaje, "%", ")")),  
            vjust=-0.9, 
            color="black", 
            hjust=0.5,
            # define text position and size
            position = position_dodge(0.9),  
            angle=0, 
            size=5.0)+
  scale_fill_discrete(name = "LUGAR", labels = c("PREPARADOR ", "TK DISOLUCION")) +   
  theme(axis.text.x = element_text(angle = 0, vjust = 1, hjust=1)) +      
  theme_bw(base_size = 14) +
  #coord_flip() +                                                         
  facet_wrap(~"DISTRIBUCIÓN DEL TURNO SEGÚN EL LUGAR DE CONSUMO")
G6

Grafico 7: Distribución de la Cantidad consumida (kg) y Cantidad Generada (kg)

set.seed(2)
par(mfrow = c(1, 2))

y1 <- datos2$Canti_gene
y2 <- datos2$Cant_consu

G7<-ggplot(datos2, aes(y = y1)) + 
  stat_boxplot(geom = "errorbar",
               width = 0.15,
               color = 1) +  # Color barras error
  geom_boxplot(fill = 3,           # Color caja
               alpha = 0.5,        # Transparencia
               color = 1,          # Color del borde
               outlier.colour = 2) +# Color atípicos
  ggtitle("CANTIDAD GENERADA") +
  xlab("") + ylab("kg") +theme(
    plot.title = element_text(color="black", size=14, face="bold"),
    axis.title.x = element_text(color="blue", size=10, face="bold"),
    axis.title.y = element_text(color="black", size=10, face="bold")
  )

G8<-ggplot(datos2, aes(y = y2)) + 
  stat_boxplot(geom = "errorbar",
               width = 0.15,
               color = 1) +  # Color barras error
  geom_boxplot(fill = 4,           # Color caja
               alpha = 0.5,        # Transparencia
               color = 1,          # Color del borde
               outlier.colour = 2) +# Color atípicos
  ggtitle("CANTIDAD CONSUMIDA") +
  xlab("") + ylab("(kg)") +theme(
    plot.title = element_text(color="black", size=14, face="bold"),
    axis.title.x = element_text(color="blue", size=14, face="bold"),
    axis.title.y = element_text(color="black", size=14, face="bold")
  )
G7 + G8
par(mfrow = c(1, 1))# Volvemos al estado original

Grafico 9: Distribución de la Cantidad Promedio Consumida según el TURNO-LUGAR-MOTIVO

Tabla_6 <- datos2 %>% group_by(Motivo,LUGAR,TURNO) %>%
  summarise(prom_can_consu=mean(Cant_consu))

G9<-ggplot(Tabla_6, aes(x=TURNO,y=prom_can_consu, color=Motivo))+
  geom_point(cex=5)+
  facet_grid(cols = vars(LUGAR))+
  theme(axis.text.x = element_text(angle = 90, hjust = 1))+
  xlab("TURNO")+
  ylab("Promedio(kg)")+
  ggtitle("CANTIDAD PROMEDIO CONSUMIDA (kg) SEGÚN TURNO-LUGAR-MOTIVO")
G9

Grafico 10: Distribución de la Cantidad Consumida (kg) según el Motivo.

set.seed(6)
par(mfrow = c(1, 2))

G10<- ggplot(Tabla_6, aes(x=prom_can_consu, fill=Motivo))+
  geom_density(alpha=0.4)+
  xlab("Promedio de Cantidad Consumida")+
  ylab("Densidad")+
  ggtitle("DISTRIBUCIÓN DE LA CANTIDAD CONSUMIDA (kg) SEGÚN EL MOTIVO")
G10

Grafico 11: Distribución de la Cantidad Consumida (kg) según el Lugar.

G11<- ggplot(Tabla_6, aes(x=prom_can_consu, fill=LUGAR))+
  geom_density(alpha=0.4)+
  xlab("Promedio de Cantidad Consumida")+
  ylab("Densidad")+
  ggtitle("DISTRIBUCIÓN DE LA CANTIDAD GENERADA (kg) \n SEGÚN EL LUGAR")
G11

Grafico 12: Distribución de la Cantidad Consumida (kg) según el Turno.

G12<- ggplot(Tabla_6, aes(x=prom_can_consu, fill=TURNO))+
  geom_density(alpha=0.4)+
  xlab("Promedio de Cantidad Consumida")+
  ylab("Densidad")+
  ggtitle("DISTRIBUCIÓN DE LA CANTIDAD CONSUMIDA (kg) \n SEGÚN EL TURNO")

#G9 + G10 +G11
#par(mfrow = c(1, 1))# Volvemos al estado original
G12

GRAFICO 13: COMPORTAMIENTO DE LA CANTIDAD CONSUMIDA EN EL TIEMPO.

datos4<-read_excel("fecha_deter.xlsx")

ts_plot(datos4,
        title = "Comportameinto de la Cantidad Consumida",
        Ytitle = "(kg)",
        Xtitle = "Fecha")

BASE #2: CONSOLIDADO

Se carga la base de datos

#datos<-read_excel("Data.xlsx")
datos<-read_excel("Data_.xlsx")

GRAFICO 1: DISTRIBUCIÓN SEGÚN SU LUGAR DE ORIGEN Y AÑO DE RECEPCIÓN

#set.seed(2)
par(mfrow = c(1, 2))

#Transformación de los datos para grafica #1
df <- datos %>% 
  group_by(ORIGEN) %>% # Variable a ser transformada
  count() %>% 
  ungroup() %>% 
  mutate(PORCENTAJES = `n` / sum(`n`)) %>% 
  arrange(PORCENTAJES) %>%
  mutate(etiquetas = scales::percent(PORCENTAJES))

#Grafico #1
g1<-ggplot(df, aes(x = "", y = PORCENTAJES, fill = ORIGEN)) +
  geom_col(color = "black") +
  geom_label(aes(label = etiquetas),
             position = position_stack(vjust = 0.5),
             show.legend = FALSE) +
  guides(fill = guide_legend(title = "ORIGEN")) + scale_color_gradient() +
  coord_polar(theta = "y") + ggtitle ("DISTRIBUCIÓN SEGÚN SU ORIGEN")
  #theme_void() 
  
#Transformación de los datos para grafico #2
df <- datos %>% 
  group_by(FECHA) %>% # Variable a ser transformada
  count() %>% 
  ungroup() %>% 
  mutate(PORCENTAJES = `n` / sum(`n`)) %>% 
  arrange(PORCENTAJES) %>%
  mutate(etiquetas = scales::percent(PORCENTAJES))

#Grafico #2
g2<-ggplot(df, aes(x = "", y = PORCENTAJES, fill = FECHA)) +
  geom_col(color = "black") +
  geom_label(aes(label = etiquetas),
             position = position_stack(vjust = 0.5),
             show.legend = FALSE) +
  guides(fill = guide_legend(title = "AÑO")) + scale_color_viridis_d() +
  coord_polar(theta = "y") + ggtitle ("AÑO DE RECEPCIÓN")
#theme_void() 
g1 + g2
par(mfrow = c(1, 1))# Volvemos al estado original

GRAFICO 2: DISTRIBUCIÓN DE ORIGEN SEGÚN EL AÑO.

"Creación de Tabla Cruzada"
[1] "Creación de Tabla Cruzada"
Tabla1 <- datos %>%
  dplyr::group_by(ORIGEN, FECHA) %>%                                  
  dplyr::summarise(Total = n()) %>%                                
  dplyr::mutate(Porcentaje = round(Total/sum(Total)*100, 1)) %>%   
  dplyr::arrange(ORIGEN)

"Grafico"
[1] "Grafico"
g3<-ggplot(Tabla1, aes(x = ORIGEN, y=Total, fill=FECHA) ) + 
  geom_bar(width = 0.9,stat="identity",                 
           position = position_dodge()) +  
  ylim(c(0,140))+
  #xlim(c(0,300)) +                  
  #ggtitle("Un título") + 
  labs(x="", y= "Frecuencias \n (Porcentajes)") +   
  labs(fill = "Sexo") +                                 
  scale_fill_manual(values = c("cyan",  "red2")) +   
  geom_text(aes(label=paste0(Total," ", "", "(", Porcentaje, "%", ")")),  
            vjust=-0.9, 
            color="black", 
            hjust=0.5,
            # define text position and size
            position = position_dodge(0.9),  
            angle=0, 
            size=5.0)+
  scale_fill_discrete(name = "AÑO", labels = c("2021 ", "2022")) +   
  theme(axis.text.x = element_text(angle = 0, vjust = 1, hjust=1)) +      
  theme_bw(base_size = 14) +
  #coord_flip() +                                                         
  facet_wrap(~"DISTRIBUCIÓN DEL ORIGEN SEGÚN EL AÑO")
g3

GRAFICO 3: DISTRIBUCIÓN DEL TIEMPO DE RESPUESTA Y NÚMERO DE PQS

#set.seed(2)
par(mfrow = c(1, 2))

y1 <- datos$PQS
y2 <- datos$TIEMPO

g4<-ggplot(datos, aes(y = y1)) + 
  stat_boxplot(geom = "errorbar",
               width = 0.15,
               color = 1) +  # Color barras error
  geom_boxplot(fill = 3,           # Color caja
               alpha = 0.5,        # Transparencia
               color = 1,          # Color del borde
               outlier.colour = 2) +# Color atípicos
  ggtitle("NÚMERO DE PQS") +
  xlab("") + ylab("(Número)") +theme(
    plot.title = element_text(color="black", size=14, face="bold"),
    axis.title.x = element_text(color="blue", size=10, face="bold"),
    axis.title.y = element_text(color="black", size=10, face="bold")
  )

g5<-ggplot(datos, aes(y = y2)) + 
  stat_boxplot(geom = "errorbar",
               width = 0.15,
               color = 1) +  # Color barras error
  geom_boxplot(fill = 4,           # Color caja
               alpha = 0.5,        # Transparencia
               color = 1,          # Color del borde
               outlier.colour = 2) +# Color atípicos
  ggtitle("TIEMPO DE RESPUESTA") +
  xlab("") + ylab("(Días)") +theme(
    plot.title = element_text(color="black", size=14, face="bold"),
    axis.title.x = element_text(color="blue", size=14, face="bold"),
    axis.title.y = element_text(color="black", size=14, face="bold")
  )
g4 + g5
par(mfrow = c(1, 1))# Volvemos al estado original

GRAFICO 4: DISTRIBUCIÓN DEL TIPO DE SOLICITUD

"Creación de tabla de cruzada para hacer el grafico con fr y porcentaje"
[1] "Creación de tabla de cruzada para hacer el grafico con fr y porcentaje"
Tabla2 <- datos %>%
  dplyr::group_by(TIPO_DE_SOLICITUD) %>%                                  
  dplyr::summarise(Total = n()) %>%                                
  dplyr::mutate(Porcentaje = round(Total/sum(Total)*100, 1)) %>%   
  dplyr::arrange(TIPO_DE_SOLICITUD)

"Grafico"
[1] "Grafico"
g6<-ggplot(Tabla2, aes(x =TIPO_DE_SOLICITUD, y=Total) ) + 
  geom_bar(width = 0.9,stat="identity",                 
           position = position_dodge(), fill="yellow3") +  
  ylim(c(0,2000))+
  #xlim(c(0,300)) +                  
  #ggtitle("Un título") + 
  labs(x="SOLICITUD", y= "Frecuencias \n (Porcentajes)")   +   
  geom_text(aes(label=paste0(Total," ", "", "(", Porcentaje, "%", ")")),  
            vjust=-0.9, 
            color="black", 
            hjust=0.5,
            # define text position and size
            position = position_dodge(0.9),  
            angle=0, 
            size=4.0) +   
  theme(axis.text.x = element_text(angle = 0, vjust = 1, hjust=1)) +      
  theme_bw(base_size = 14) +
  #coord_flip() +                                                         
  facet_wrap(~"DISTRIBUCIÓN SEGÚN EL TIPO DE SOLICITUD")
g6

GRAFICO 5: DESCRIPCIÓN DEL MOTIVO.

#par(mfrow = c(1, 2))
#Nubes de Palabra de MOTIVO

#cargamos las librerias correspondientes
library(tm)
library(NLP)
library(SnowballC)
library(RColorBrewer)
library(wordcloud)


#Que palabras hay con mayor frecuencia en los comentarios para .....
#nuestro texto lo guardamos en bloc de notas en formato txt

texto <- readLines("MOTIVO.txt")
texto = iconv(texto, to="ASCII//TRANSLIT")
texto = Corpus(VectorSource(texto)) 

########### LIMPIAMOS NUESTRO TEXTO CON EL COMANDO tm_map

#ponemos todos los datos a minuscula (A!=a)
discurso=tm_map(texto, tolower)
#quitamos los espacios en blanco
discurso =tm_map(discurso, stripWhitespace)
#quitamos la puntuacion
discurso = tm_map(discurso, removePunctuation)
#quitamos los numeros
discurso = tm_map(discurso, removeNumbers)

#mostramos palabras vacias y genericas
#stopwords("spanish")
#quitamos palabras genericas
discurso=tm_map(discurso, removeWords,stopwords("spanish"))


#tambien podemos tener nuestra propia lista de palabras a quitar

############### DATA FRAME DE PALABRAS CON SU FRECUENCIA

#Creamos matriz de letras
letras= TermDocumentMatrix(discurso)
findFreqTerms(letras, lowfreq=5)
 [1] "asesorias"     "consulta"      "dotacion"      "pago"         
 [5] "ruta"          "certificados"  "volantes"      "asesoria"     
 [9] "prestamos"     "tramite"       "cesantias"     "auxilio"      
[13] "lentes"        "almuerzo"      "nacimiento"    "afiliaciones" 
[17] "seguridad"     "social"        "traslados"     "pagos"        
[21] "fallecimiento" "calamidad"     "prestamo"      "antiguedad"   
[25] "prima"         "contrato"      "encargos"      "matrimonio"   
[29] "programacion"  "extras"        "horas"         "recargos"     
matrix=as.matrix(letras)

#lo ordenamos y sumamos las letras de nuestra matriz
vector <- sort(rowSums(matrix),decreasing=TRUE) 
#creamos la data con las palabras y su frecuencia
dataletras <- data.frame(word= names(vector),frequencia=vector) 
# lo nombra y le da formato de data.frame

############ GRAFICAMOS LA NUBE DE PALABRAS
N1<-wordcloud(words = dataletras$word, freq = dataletras$freq, min.freq = 1,
          max.words=100000)
#En el centro la palabra mas importante, 
N<-wordcloud(words = dataletras$word, freq = dataletras$freq, min.freq = 1,
          max.words=100000, random.order=FALSE, rot.per=0.2,
          colors=brewer.pal(8, "Set1"))

N1
NULL

GRAFICO 6: DESCRIPCIÓN DEL CARGO.

texto <- readLines("CARGO.txt")
texto = iconv(texto, to="ASCII//TRANSLIT")
texto = Corpus(VectorSource(texto)) 

########### LIMPIAMOS NUESTRO TEXTO CON EL COMANDO tm_map

#ponemos todos los datos a minuscula (A!=a)
discurso=tm_map(texto, tolower)
#quitamos los espacios en blanco
discurso =tm_map(discurso, stripWhitespace)
#quitamos la puntuacion
discurso = tm_map(discurso, removePunctuation)
#quitamos los numeros
discurso = tm_map(discurso, removeNumbers)

#mostramos palabras vacias y genericas
#stopwords("spanish")
#quitamos palabras genericas
discurso=tm_map(discurso, removeWords,stopwords("spanish"))


#tambien podemos tener nuestra propia lista de palabras a quitar

############### DATA FRAME DE PALABRAS CON SU FRECUENCIA

#Creamos matriz de letras
letras= TermDocumentMatrix(discurso)
findFreqTerms(letras, lowfreq=5)
  [1] "auxiliar"        "produccion"      "confiabi"       
  [4] "enfasis"         "impresora"       "rotomec"        
  [7] "cortadora"       "operario"        "jefe"           
 [10] "coordinador"     "laminacion"      "calidad"        
 [13] "preprensa"       "famm"            "montadora"      
 [16] "laminadora"      "desarrollo"      "soporte"        
 [19] "tecnico"         "supernumerario"  "relevo"         
 [22] "tintas"          "administrativo"  "abastecimiento" 
 [25] "analista"        "coordinadora"    "vitalidad"      
 [28] "administrador"   "cuenta"          "disponibilidad" 
 [31] "promotor"        "refrigeracion"   "humanos"        
 [34] "recursos"        "boceteador"      "plancha"        
 [37] "locativas"       "inventario"      "contable"       
 [40] "gestor"          "programacion"    "logistico"      
 [43] "comunicaciones"  "mod"             "comercio"       
 [46] "exterior"        "gestora"         "ingenieroa"     
 [49] "proyectos"       "desprendimiento" "lavado"         
 [52] "pla"             "nomina"          "software"       
 [55] "mantenimiento"   "planeacion"      "profesional"    
 [58] "control"         "hsei"            "riesgos"        
 [61] "pcmc"            "chief"           "customer"       
 [64] "officer"         "bienestar"       "bobst"          
 [67] "montaje"         "sellado"         "ayudante"       
 [70] "impresion"       "back"            "office"         
 [73] "presidente"      "lider"           "kam"            
 [76] "senior"          "ingeniero"       "cuentas"        
 [79] "ejecutivo"       "aprendiz"        "gestion"        
 [82] "organizacional"  "comercial"       "financiero"     
 [85] "gerente"         "chain"           "director"       
 [88] "supply"          "colaborador"     "servicio"       
 [91] "operaciones"     "selladora"       "wicket"         
 [94] "corte"           "fischer"         "carta"          
 [97] "color"           "facturacion"     "materiales"     
[100] "finalizador"     "distribucion"    "destiladora"    
[103] "compras"         "publicas"        "relaciones"     
[106] "mecanico"        "humano"          "peletizadora"   
[109] "electronico"     "revision"        "investigacion"  
[112] "cyrel"           "industri"        "aseo"           
[115] "oficinas"        "erp"             "atf"            
[118] "extrusora"       "asuntos"         "humana"         
[121] "legales"         "anilox"          "tornero"        
[124] "manufactura"     "conductor"       "paletizado"     
[127] "especialista"    "exportaciones"   "administrativos"
[130] "servicios"       "continua"        "mejora"         
[133] "extruder"        "talento"         "estandarizacion"
[136] "grafico"         "planchas"       
matrix=as.matrix(letras)

#lo ordenamos y sumamos las letras de nuestra matriz
vector <- sort(rowSums(matrix),decreasing=TRUE) 
#creamos la data con las palabras y su frecuencia
dataletras <- data.frame(word= names(vector),frequencia=vector) 
# lo nombra y le da formato de data.frame

############ GRAFICAMOS LA NUBE DE PALABRAS
N2<-wordcloud(words = dataletras$word, freq = dataletras$freq, min.freq = 1,
          max.words=100000)
#en el centro la palabra mas importante, 
N2<-wordcloud(words = dataletras$word, freq = dataletras$freq, min.freq = 1,
          max.words=100000, random.order=FALSE, rot.per=0.2,
          colors=brewer.pal(8, "Dark2"))

N2
NULL

GRAFICO 7: DISTRIBUCÓN DE SOLICITUD SEGÚN EL MES

g7<-ggplot(datos, aes(fct_infreq(PERIODO))) +                      #1
  #geom_bar() +                                             #2
  geom_bar(width=0.9, colour="black", fill="yellow2") +       #2 
  
  labs(x="",y= "Frecuencia")  +              #3               
  ylim(c(0,330)) +                               #4
  #xlim(c(0,300)) +                              #4
  ggtitle("")  +               #5
  
  # theme_bw() +                                 #6
  theme_bw(base_size = 12) +                     #6
  #coord_flip() +                                #7
  
  geom_text(aes(label=..count..), stat='count',  #8
            position=position_dodge(width=0.9), 
            vjust=-0.25, 
            size=5.0) + 
  facet_wrap(~"NÚMERO DE SOLICITUD SEGÚN EL MES") 
g7

GRAFICO 8: DISTRIBUCIÓN SEGÚN EL MEDIO

"Creación de tabla de cruzada para hacer el grafico con fr y porcentaje"
[1] "Creación de tabla de cruzada para hacer el grafico con fr y porcentaje"
Tabla3 <- datos %>%
  dplyr::group_by(MEDIO) %>%                                  
  dplyr::summarise(Total = n()) %>%                                
  dplyr::mutate(Porcentaje = round(Total/sum(Total)*100, 1)) %>%   
  dplyr::arrange(MEDIO)

"Grafico"
[1] "Grafico"
g8<-ggplot(Tabla3, aes(x =MEDIO, y=Total) ) + 
  geom_bar(width = 0.9,stat="identity",                 
           position = position_dodge(), fill="cyan3") +  
  ylim(c(0,1400))+
  #xlim(c(0,300)) +                  
  #ggtitle("Un título") + 
  labs(x="MEDIO", y= "Frecuencias \n (Porcentajes)")   +   
  geom_text(aes(label=paste0(Total," ", "", "(", Porcentaje, "%", ")")),  
            vjust=-0.9, 
            color="black", 
            hjust=0.5,
            # define text position and size
            position = position_dodge(0.9),  
            angle=0, 
            size=5.0) +   
  theme(axis.text.x = element_text(angle = 0, vjust = 1, hjust=1)) +      
  theme_bw(base_size = 14) +
  #coord_flip() +                                                         
  facet_wrap(~"DISTRIBUCIÓN SEGÚN EL MEDIO")
g8

GRAFICO 9: DISTRIBUCIÓN SEGÚN EL CLIENTE

"Creación de tabla de cruzada para hacer el grafico con fr y porcentaje"
[1] "Creación de tabla de cruzada para hacer el grafico con fr y porcentaje"
Tabla4 <- datos %>%
  dplyr::group_by(CLIENTE) %>%                                  
  dplyr::summarise(Total = n()) %>%                                
  dplyr::mutate(Porcentaje = round(Total/sum(Total)*100, 1)) %>%   
  dplyr::arrange(CLIENTE)

"Grafico"
[1] "Grafico"
g9<-ggplot(Tabla4, aes(x =CLIENTE, y=Total) ) + 
  geom_bar(width = 0.9,stat="identity",                 
           position = position_dodge(), fill="blue3") +  
  ylim(c(0,1850))+
  #xlim(c(0,300)) +                  
  #ggtitle("Un título") + 
  labs(x="CLIENTE", y= "Frecuencias \n (Porcentajes)")   +   
  geom_text(aes(label=paste0(Total," ", "", "(", Porcentaje, "%", ")")),  
            vjust=-0.9, 
            color="black", 
            hjust=0.5,
            # define text position and size
            position = position_dodge(0.9),  
            angle=0, 
            size=5.0) +   
  theme(axis.text.x = element_text(angle = 0, vjust = 1, hjust=1)) +      
  theme_bw(base_size = 14) +
  #coord_flip() +                                                         
  facet_wrap(~"DISTRIBUCIÓN SEGÚN EL CLIENTE")
g9

GRAFICO 10: DISTRIBUCIÓN SEGÚN EL ESTADO DE LA SOLICITUD.

"Creación de tabla de cruzada para hacer el grafico con fr y porcentaje"
[1] "Creación de tabla de cruzada para hacer el grafico con fr y porcentaje"
Tabla6 <- datos %>%
  dplyr::group_by(ESTADO) %>%                                  
  dplyr::summarise(Total = n()) %>%                                
  dplyr::mutate(Porcentaje = round(Total/sum(Total)*100, 1)) %>%   
  dplyr::arrange(ESTADO)

"Grafico"
[1] "Grafico"
g10<-ggplot(Tabla6, aes(x =ESTADO, y=Total) ) + 
  geom_bar(width = 0.9,stat="identity",                 
           position = position_dodge(), fill="orange") +  
  ylim(c(0,2200))+
  #xlim(c(0,300)) +                  
  #ggtitle("Un título") + 
  labs(x="ESTADO", y= "Frecuencias \n (Porcentajes)")   +   
  geom_text(aes(label=paste0(Total," ", "", "(", Porcentaje, "%", ")")),  
            vjust=-0.9, 
            color="black", 
            hjust=0.5,
            # define text position and size
            position = position_dodge(0.9),  
            angle=0, 
            size=5.0) +   
  theme(axis.text.x = element_text(angle = 0, vjust = 1, hjust=1)) +      
  theme_bw(base_size = 14) +
  #coord_flip() +                                                         
  facet_wrap(~"DISTRIBUCIÓN SEGÚN EL ESTADO DE LA SOLICITUD")
g10

GRAFICO 11: DISTRIBUCIÓN DEL MEDIO SEGÚN EL CLIENTE.

"Creación de Tabla Cruzada"
[1] "Creación de Tabla Cruzada"
Tabla5 <- datos %>%
  dplyr::group_by(MEDIO, CLIENTE) %>%                                  
  dplyr::summarise(Total = n()) %>%                                
  dplyr::mutate(Porcentaje = round(Total/sum(Total)*100, 1)) %>%   
  dplyr::arrange(MEDIO)

"Grafico"
[1] "Grafico"
g11<-ggplot(Tabla5, aes(x = MEDIO, y=Total, fill=CLIENTE) ) + 
  geom_bar(width = 0.9,stat="identity",                 
           position = position_dodge()) +  
  ylim(c(0,1350))+
  #xlim(c(0,300)) +                  
  #ggtitle("Un título") + 
  labs(x="", y= "Frecuencias \n (Porcentajes)") +   
  labs(fill = "CLIENTE") +                                 
  scale_fill_manual(values = c("pink",  "skyblue")) +   
  geom_text(aes(label=paste0(Total," ", "", "(", Porcentaje, "%", ")")),  
            vjust=-0.9, 
            color="black", 
            hjust=-0.5,
            # define text position and size
            position = position_dodge(0.9),  
            angle=0, 
            size=4.0)+
  scale_fill_discrete(name = "CLIENTE", labels = c("LITOPLAS S.A", "POLYREC S.A.S", "POLYREC ZF S.A.S", "POLYREC")) +   
  theme(axis.text.x = element_text(angle = 0, vjust = 1, hjust=1)) +      
  theme_bw(base_size = 14) +
  coord_flip() +                                                         
  facet_wrap(~"DISTRIBUCIÓN DEL MEDIO SEGÚN EL CLIENTE")
g11

GRAFICO 12: COMPORTAMIENTO DEL TIEMPO DE RESPUESTA.

datos3<-read_excel("Tiempo_respuesta.xlsx")

ts_plot(datos3,
        title = "Comportameinto del Tiempo de Respuesta (Días)",
        Ytitle = "Días",
        Xtitle = "Fecha")