Librerias

Es importante cargar las siguientes librerias:

library(cowplot)
library(ggthemes)
library(readxl)
library(tidyverse)
library(ggplot2)
library(dplyr)
library(writexl)
library(kableExtra)
library(knitr)
library(rmarkdown)
library(RColorBrewer)
library(tinytex)
library(janitor)
library(rsconnect)
library(stringr)
library(forcats)
library(ggthemes)
library(lubridate)
library(magrittr)
library(data.table)
library(dslabs)
#devtools::install_github('Mikata-Project/ggthemr', force = TRUE)
library(ggthemr)
library(scales)
library(ggpubr)
library(extrafont)
library(ggrepel)
library(zoo)
library(gridExtra)

Gráficos barras

Para este ejercicio contamos con la siguiente base de datos:

ROE- Países de la Región
Country Marzo 2020
Argentina 13
Bolivia 9
Brasil 12
Chile 11
Colombia 11
Ecuador 8
Paraguay 14
Perú 14
Uruguay 44
Fuente: FELABAN

Gráfico No1

Arrancamos con un gráfico sencillo de barras, para aquello, y siguiendo los linemientos establecidos en la visualización de los datos, presentamos la informAción de forma ascendente, para esto aplicamos, la siguiente rutina.

  • Donde:

aes: Se detalla el eje de los gráficos.

geom_bar: Esta opción permite hacer diagrama de barras.

width: Ancho de las barras

fill: Color de las barras

scale_y_continuous(limits = c(0,45)): Límites del eje y.

theme(plot.title = element_text(hjust=0.5: Al poner hjust=0.5, es posible centrar el titúlo del gráfico

aa <- ggplot(data=ROE, aes(x=Country, y =`Marzo 2020`))

aa <- aa + geom_bar(stat = "identity", width = 0.4, fill= "bisque3")+
      theme_wsj() +  scale_y_continuous(limits = c(0,45))
     

aa <- aa + labs(title    = "ROE: Países de la región",
                caption  = "Fuente:FELABAN") + 
      theme(plot.title   =  element_text(hjust=0.5, size =15, face = "bold" ),
            plot.caption =  element_text(size = 9)) 
aa

Gráfico No2

fill: En este caso, al aplicar fill, dentro de la opción aes, estamos indicando que cada barra (país), tendrá un color específico

colour: Al aplicar colour dentro de geom_bar, estamos indicando que queremos que las barras presenten líneas color gray2

scale_fill_manual: Debemos elegir los colores de cada país. En este caso, todos los países presentaran el color cadetblue1, mientras que Argentina steelblue.

theme_classic(): Un tema de aspecto clásico, con líneas de eje xey y sin líneas de cuadrícula.

axis.title.x = element_blank(): Como se activo previamente theme_classic, al aplicar axis.title.x = element_blank(),indicamos que no exhiba la etiqueta del eje x.

ab <- ggplot(ROE, aes(x= Country, y= `Marzo 2020`, fill = Country))

ab <- ab + geom_bar(stat = "identity", colour="gray2", width = 0.5) +
      scale_fill_manual(values = c("cadetblue1","cadetblue1","cadetblue1",
                                   "steelblue","cadetblue1","cadetblue1",
                                   "cadetblue1","cadetblue1","cadetblue1")) +
       theme_classic()

ab <- ab + labs(title    = "ROE: Países de la región",
                caption  = "Fuente:FELABAN") +
  
        theme(plot.title =  element_text(hjust=0.5, size =15, face = "bold" ),
        plot.caption     =  element_text(size = 9),
        legend.position  = 'none',
        axis.title.x = element_blank(),
        axis.title.y = element_blank()) 
ab

Gráfico No3: theme_economist()

theme_economist(): Gráficos de estilo similares a los de la revista The Economist.

ac <- ggplot(data=ROE, aes(x= Country, y= `Marzo 2020`))

ac <- ac + geom_bar(stat = "identity", width = 0.6, fill= "cadetblue3")+
      ylab("En porcentajes [%]")+xlab(NULL) + theme_economist()+
      scale_y_continuous(limits = c(0,45))

ac <- ac + labs(title    = "ROE: Países de la región") + 
     theme(plot.title    =  element_text(hjust=0.5, size =15, face = "bold" ),
           plot.caption  =  element_text(hjust = 1, size =8)) 
ac

Gráfico No4: Barras Invertidas

reorder Permite ordenar de forma ascendente la variable Productos de acuerdo a sus valores expresados en Millosd USD.

aes(…label): Esta opción permite exhibir las etiquetas de cada producto.

scale_y_continuous(…, expand = c(0,0)): Permite que el gráfico comience en la coordenada (0,0).

coord_flip(): Esta opción permite girar la dimensión del gráfico.

position_dodge: Permite ajustar las etiquetas. Con la opción dodge, Ordena una a lado de la otra.

ad <- ggplot(data = Exportaciones, aes(x=reorder(Productos, `Millones USD FOB`),
                                       y= `Millones USD FOB`, fill= Productos, 
                                  label = `Millones USD FOB`)) +
                                       
      geom_bar(stat = "identity", colour="gray2", width = 0.8) + scale_y_continuous(limits = c(0,5000), expand                                                                                                = c(0,0)) +
      scale_fill_manual(values = c("darkblue","darkblue","darkblue","darkblue"
                                   ,"darkblue","darkblue","darkblue","darkblue","darkblue"
                                   ,"darkblue","darkblue"))+
      coord_flip() + theme_classic()

ad <- ad + labs(title    = "Exportaciones FOB por producto principal",
                caption  = "Fuente:BCE") +
  
  theme(plot.title       =  element_text(hjust=0.5, size =15, face = "bold" ),
        plot.caption     =  element_text(size = 8),
        legend.position  = 'none',
        axis.title.y     =  element_blank())
        
ad <- ad + geom_text(position = position_dodge(width= 1), vjust= 0.5, hjust = -0.1, size=4)

ad

Gráfico No5: Barras- Caso Especial

Year Score
2015 270
2016 275
2017 280
2018 300
2019 350

Existen ocasiones en los cuales, al aplicar un gráfico de barras, los mismos no son reconocidos por el software, para lo cual, se considera como factor al eje x, que en este caso, es representado por la variable year

theme (axis.title = element_text(size = 9): Permite cambiar el tamaño de letra de ambos títulos de los ejes.

theme (axis.text.x = element_text(colour=“black”, size = 14): Permite cambiar el tamaño de letra de los elementos que integran el eje x.

ab <- ggplot(PI, aes(x= Year, y= Score, fill= as.factor(Year)))

ab <- ab + geom_bar(stat = "identity", colour="gray2", width = 0.5) +
           scale_y_continuous(limits = c(0,400), expand= c(0,0))+
           scale_fill_manual(values = c("lightskyblue1",
                                       "lightskyblue1",
                                       "lightskyblue3",
                                       "dodgerblue3",
                                       "dodgerblue3")) +
          ylab("Score") + xlab('Year')

ab <- ab +  theme(axis.line        = element_line(size=1, colour = "black"),
                  panel.grid.minor = element_blank(),
                  panel.border     = element_blank(), 
                  panel.background = element_blank(),
                  text             = element_text(family="mono"),
                  axis.text.x      = element_text(colour="black", size = 14),
                  axis.text.y      = element_text(colour="black", size = 14),
                  axis.title       = element_text(size = 15))
## Warning: The `size` argument of `element_line()` is deprecated as of ggplot2 3.4.0.
## i Please use the `linewidth` argument instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
ab <- ab + theme(legend.position ="bottom", 
                 legend.direction="horizontal",
                 legend.title    = element_blank())

ab <- ab  + geom_text(position = position_dodge(width= 0.9), vjust= -0.28,size=6,
                      aes(label=format(Score,
                                       big.mark = ".", decimal.mark= ",")))

ab

Gráfico No6: Barras - Inclusión flechas ejes

theme(legend.position =“none”,axis.line = element_line(arrow = arrow())): El primer argumento permite eliminar las etiquetas de las variable Year (categorizado como factor). Mientras que el segundo factor, permite poner en ambos ejes una flecha que señala el infinito.

abl <- ggplot(PI, aes(x= Year, y= Score, fill= as.factor(Year)))

abl <- abl + geom_bar(stat = "identity", colour="gray2", width = 0.5) +
           scale_y_continuous(limits = c(0,400), expand= c(0,0))+
           scale_fill_manual(values = c("lightskyblue1",
                                       "lightskyblue1",
                                       "lightskyblue3",
                                       "dodgerblue3",
                                       "dodgerblue3")) +
          ylab("Score") + xlab('Year')

abl <- abl +  theme(axis.line      = element_line(size=1, colour = "black"),
                  panel.grid.minor = element_blank(),
                  panel.border     = element_blank(), 
                  panel.background = element_blank(),
                  text             = element_text(family="mono"),
                  axis.text.x      = element_text(colour="black", size = 14),
                  axis.text.y      = element_text(colour="black", size = 14),
                  axis.title       = element_text(size = 15))
 
abl <- abl + theme(legend.position ="none",
                 axis.line       = element_line(arrow = arrow()))

abl <- abl  + geom_text(position = position_dodge(width= 0.9), vjust= -0.28,size=6,
                      aes(label=format(Score,
                                       big.mark = ".", decimal.mark= ",")))
abl

Gráfico No7: Categorías

Para este ejercicio contamos con la siguiente base de datos:

Exportaciones-Continente
fecha Continente Exportaciones
2012-11-16 América 76.805
2012-11-16 Europa 51.990
2012-11-16 Asia 88.020
2014-05-31 Europa 65.590
2014-05-31 Asia 82.890
2014-05-31 América 63.640
2020-12-14 Europa 89.190
2020-12-14 Asia 80.660
2020-12-14 América 60.540
Fuente: FEF

geom_col: Esta opción permite generar gráficos de barras, el cual contega categorias (en este caso a los continentes).

aes(x=factor(fecha): Como la variable fecha, está integrado por fechas no continuas, se recomienda transformar la varible tipo date a factor

geom_text,… vjust:-0.25: Al aplicar esta opción, las etiquetas de las cifras, se exhiben en la parte superior de la barra.

ae <- ggplot(data=jjj, aes(x=factor(fecha), y = Exportaciones, fill=Continente,
                                        label = Exportaciones)) + 
      geom_col(position = "dodge", width = 0.9)  + theme_classic() + scale_fill_manual(values = c("darkgray","cadetblue1", "mediumpurple4")) + scale_y_continuous(limits = c(0,100), expand = c(0,0))
                                                                                      
ae <- ae + labs(title      = "Nivel de Exportaciones ",
                caption    = "Fuente:OEA") +
  theme(plot.title         =  element_text(hjust=0.5, size =15, face = "bold"),
        plot.caption       =  element_text(size = 8),
        legend.position    = 'bottom',
        legend.title       =  element_blank(),
        axis.title.x       =  element_blank(),
        axis.title.y       =  element_blank(),
        text = element_text(size = 14))

ae <- ae + geom_text(position = position_dodge(width= 0.9), vjust= -0.25, size=5)

ae

Gráfico No7.1: scale_fill_brewer

scale_fill_brewer: Esta opción genera un abanico de posibilidades de colores para las categorias. theme_stata: Gráficos en formato Stata.

af <- ggplot(data=jjj, aes(x=factor(fecha), y = Exportaciones, fill=Continente,
                           label = Exportaciones)) + 
  geom_col(position = "dodge", width = 0.9, colour="gray2") + theme_stata() + scale_fill_brewer(palette="Pastel1") + 
  scale_y_continuous(limits = c(0,100), expand = c(0,0)) 

af <- af + labs(title      = "Nivel de Exportaciones ",
                caption    = "Fuente:OEA") +
  theme(plot.title         =  element_text(hjust=0.5, size =15, face = "bold"),
        plot.caption       =  element_text(size = 8),
        legend.position    = 'bottom',
        legend.title       =  element_blank(),
        axis.title.x       =  element_blank(),
        axis.title.y       =  element_blank(),
        text               = element_text(size = 14))

af <- af + geom_text(position = position_dodge(width= 0.9), vjust= -0.25, size=5)

af

Gráfico No7.1.1: scale_fill_brewer-fct_relevel

fct_relevel: Permite ordenar los factores de acuerdo al criterio dell investigador.

af <- ggplot(data=jjj, aes(x=factor(fecha), y = Exportaciones, fill=fct_relevel(Continente, 'Asia', 'América', 'Europa'),
                           label = Exportaciones)) + 
  geom_col(position = "dodge", width = 0.9, colour="gray2") + theme_stata() +    scale_fill_brewer(palette="Set3") + scale_y_continuous(limits = c(0,100), expand = c(0,0)) 

af <- af + labs(title      = "Nivel de Exportaciones ",
                caption    = "Fuente:OEA") +
  theme(plot.title         =  element_text(hjust=0.5, size =15, face = "bold"),
        plot.caption       =  element_text(size = 8),
        legend.position    = 'bottom',
        legend.title       =  element_blank(),
        axis.title.x       =  element_blank(),
        axis.title.y       =  element_blank(),
        text = element_text(size = 14))

af <- af + geom_text(position = position_dodge(width= 0.9), vjust= -0.25, size=5)

af

Gráfico No7.2: Solución Etiquetas largas

La tabla que se presenta a continuación exhibe etiquetas bastantes extensas, lo cual provocaría que al realizar el gráfico correspondiente, no exponga un gráfico agradable para su presentación.

Ejemplo Tabla con etiquetas grandes
Variable_one Variable_two
etiqueta grande 15
etiqueta aún más grande 23
Una etiqueta extremadamente grande 34
Grande, la más grande 21
Otra etiqueta 13
corta 5
Fuente: SB

Para solucionar ese inconveniente aplicamos la siguiente rutina:

scale_x_discrete(guide = ggplot2::guide_axis(n.dodge = 1), labels = function(x) stringr::str_wrap(x, width = 10))

  • Con la opción width, elige la longitud del caracter, para ubicarlo en una segunda fila en el gráfico, en este caso, la ocpión por default es 10.

  • text = element_text(size = 9): Modifica el tamaño de letra de las etiquetas.

ac <- ggplot(data=dfpl, aes(x= Variable_one, y= Variable_two))

ac <- ac + geom_bar(stat = "identity", width = 0.6)+ theme_economist() + scale_colour_economist()

ac <- ac + scale_x_discrete(guide = ggplot2::guide_axis(n.dodge = 1), 
                              labels = function(x) stringr::str_wrap(x, width = 10))

ac <- ac + ggtitle("Etiquetas extensas")+
           theme(legend.position = "bottom", legend.direction = "horizontal",
                 legend.title    = element_blank(),
                 axis.title.x    = element_blank(),
                 axis.title.y    = element_blank(),
                 text = element_text(size = 9),
                 plot.title      = element_text(hjust = 0.5, size = 15, face= "bold"))

ac       

Gráfico No7.3: Solución Etiquetas largas (Versión II)

area Razones Proporcion
Norte Desea que esté al cuidado de la madre/padre u otro familiar 69.84
Sur Desea que esté al cuidado de la madre/padre u otro familiar 57.97
Sur no hay colegios en el barrio 17.44
Norte no lo considera necesario 16.56
Sur no lo considera necesario 12.59
Sur otra razón, cuá? 6.10
Norte otra razón, cuá? 5.37
Sur no hay vacantes en colegios del barrio 4.29
Norte no hay colegios en el barrio 4.03
Norte no hay vacantes en colegios del barrio 3.03

Para este ejercicio necesitamos activar la libreria scales

regi <- c("darkslateblue", "goldenrod4")

GR <- ggplot(data=no_asiste_area, aes(reorder(Razones,-Proporcion), Proporcion, 
                                           fill=area,
                                           label = Proporcion)) + 
           geom_col(position = "dodge", width = 0.8,colour="black") 

GR <- GR + theme(legend.position="bottom", 
                           legend.direction="horizontal",
                           legend.title = element_blank()) +
  labs(x="",y="En porcentajes [%]") + 
  scale_y_continuous(limits = c(0,80), expand = c(0,0))+ 
  scale_fill_manual(values=regi) +
  theme(axis.line = element_line(size=0.8, colour = "black"),
        #panel.grid.major = element_line(colour = "#d3d3d3"), 
        panel.grid.minor = element_blank(),
        panel.border = element_blank(), panel.background = element_blank()) +
  theme(plot.title = element_text(hjust = 0.5,size = 15, family = "Comic Sans MS", 
                                  face = "bold"),
        text=element_text(family="Comic Sans MS"),
        axis.text.x=element_text(colour="black", size = 9),
        axis.text.y=element_text(colour="black", size = 10))+
  geom_text(position = position_dodge(width= 0.8), vjust= -0.28,size=3,
            aes(label=format(Proporcion,
                             big.mark = ".",
                             decimal.mark= ",")))

GR <- GR + scale_x_discrete(labels = wrap_format(15))
GR

Gráfico No8: Barras apiladas

Para este ejercicio contamos con la siguiente base de datos:

Composición Activos
CÓDIGO CUENTA Años Volumen Composicion
14 Cartera de créditos 2016-12 19008.58 57.85
11 Fondos Disponibles 2016-12 8217.27 25.01
13 Inversiones 2016-12 5635.11 17.15
14 Cartera de créditos 2017-12 22894.51 63.64
11 Fondos Disponibles 2017-12 7372.27 20.49
13 Inversiones 2017-12 5709.87 15.87
14 Cartera de créditos 2018-12 25550.37 67.47
11 Fondos Disponibles 2018-12 6955.59 18.37
13 Inversiones 2018-12 5361.94 14.16
Fuente: SB

scale_fill_manual(values = filla): Los colores se especifican de acuerdo al criterio del consultor

filla <- c("goldenrod2","dodgerblue4", "firebrick4")

ag <- ggplot(data = Blades, aes(y=Composicion, x=Años, fill=CUENTA))+
      geom_bar(stat= "identity", width = 0.5)+ xlab('Años')+ ylab('Porcentajes[%]') + scale_y_continuous(expand = c(0,0))+ 
      
      geom_text(aes(Años, label=paste0(Composicion,'%')),
      colour= 'white', position= position_stack(vjust = 0.5)) +
      labs(fill='Cuentas')+ theme_bw()+ ggtitle("Composición Activos")+
      theme(legend.position = "bottom", legend.direction = "horizontal",
            legend.title    = element_blank(),
            plot.title      = element_text(hjust = 0.5, size = 15, face= "bold"))+
      scale_fill_manual(values = filla)
                        
ag        

Gráfico No8.1: Barras apiladas- Theme_Economist

ah <- ggplot(data = Blades, aes(y=Composicion, x=Años, fill=CUENTA))+
      geom_bar(stat= "identity", width = 0.5)+ xlab('Años')+ ylab('Porcentajes[%]') + scale_y_continuous(expand = c(0,0))+ 
      
      geom_text(aes(Años, label=paste0(Composicion,'%')),
      colour= 'white', position= position_stack(vjust = 0.5)) +
      labs(fill='Cuentas')+ theme_economist()+ scale_fill_economist()+ ggtitle("Composición Activos")+
      theme(legend.position = "bottom", legend.direction = "horizontal",
            legend.title    = element_blank(),
            plot.title      = element_text(hjust = 0.5, size = 15, face= "bold"))
                        
ah        

Gráfico No8.2: Barras apiladas- Theme Wall Street

ai <- ggplot(data = Blades, aes(y=Composicion, x=Años, fill=CUENTA))+
      geom_bar(stat= "identity", width = 0.5)+ xlab('Años')+ ylab('Porcentajes[%]') + scale_y_continuous(expand = c(0,0))+ 
      
      geom_text(aes(Años, label=paste0(Composicion,'%')),
      colour= 'white', position= position_stack(vjust = 0.5)) +
      labs(fill='Cuentas')+ theme_wsj()+ scale_fill_wsj('colors6')+ ggtitle("Composición Activos")+
      theme(legend.position = "bottom", legend.direction = "horizontal",
            legend.title    = element_blank(),
            plot.title      = element_text(hjust = 0.5, size = 15, face= "bold"))
                        
ai        

Gráfico No8.3: Barras apiladas- Tema propio

regi <- c("blue4", "firebrick", "gray59")

aj <- ggplot(data = Blades, aes(y=Composicion, x=Años, fill=CUENTA))+
      geom_bar (stat="identity", width = 0.5, colour="gray2")+
      scale_y_continuous(limits = c(0,101),expand = c(0,0))+
      geom_text(aes(x = Años, y = Composicion, label = paste0(Composicion,'%')), colour="white",
                family="Tahoma", size = 4, position= position_stack(vjust = 0.5)) +
      theme(legend.position="bottom", legend.direction="horizontal",
            legend.title = element_blank()) +
      labs(x="Años", y="Porcentaje [%]") +
      ggtitle("Composición Activos") +
      scale_fill_manual(values=regi) +
  theme(axis.line = element_line(size=1, colour = "black"),
        panel.grid.major = element_line(colour = "#d3d3d3"), panel.grid.minor = element_blank(),
        panel.border = element_blank(), panel.background = element_blank()) +
  theme(plot.title = element_text(hjust = 0.5,size = 15, family = "Comic Sans MS", face = "bold"),
        text=element_text(family="Comic Sans MS"),
        axis.text.x=element_text(colour="black", size = 10),
        axis.text.y=element_text(colour="black", size = 10))
aj

Gráfico No8.4: Barras apiladas- Theme Stata

ak <- ggplot(data = Blades, aes(y=Composicion, x=Años, fill=CUENTA))+
      geom_bar(stat= "identity", width = 0.5,colour="gray2")+
      xlab('Años')+ ylab('Porcentajes[%]') +scale_y_continuous(expand = c(0,0)) +
      
      geom_text(aes(x=Años, label=paste0(Composicion, '%')),
                colour= 'black', position= position_stack(vjust = 0.5)) +
      labs(fill='Cuentas')+ theme_stata() + scale_fill_brewer(palette="Pastel1")+
      ggtitle("Composición Activos")+
      theme(legend.position = "bottom", legend.direction = "horizontal",
            legend.title    = element_blank()) + 
      theme(plot.title = element_text(hjust = 0.5, size = 15, face= "bold"))
ak    

Gráfico No8.5: Barras apiladas - libreria ggthemr

El presente gráfico persigue varios objetivos:

  • Que el tipo de barras vaya de acuerdo con la etiqueta de Correctas e Incorrectas:Para esto previamente, se debe realizar el siguiente ajuste a la base de datos:

mutate(Tipo = factor(Tipo, levels = c(“Incorrectas”,“Correctas”), labels = c(“Incorrectas”,“Correctas”)))

  • Así mismo, dentro de la rutina, para que se cumpla con el obetivo principal, se debe aplicar lo siguiente: guides(fill = guide_legend(reverse = TRUE))

  • theme(axis.text.y = element_text(size = 13) : Modifica el tamaño de las etiquetas del eje y (el mismo procedimiento para el eje x).

  • axis.line = Gráfica el eje x & y.

load("D:/Documentos/Estadisticos/R/R_studio/Markdown/Ggplot/Tabla_one.RData")

ak <- ggplot(data = Tabla_one, aes(y=Composición, x=Materias, fill=factor(Aciertos)))+
         geom_bar(stat= "identity",position="stack",
                  width = 0.5,colour="gray2")+
         guides(fill = guide_legend(reverse = TRUE)) +
         labs(fill='Tipo')+  
         ylab('Porcentajes[%]') +scale_y_continuous(expand = c(0,0)) +
         geom_text(aes(x=Materias, label=paste0(Composición, '%')), size= 6,
                   colour= 'black', position= position_stack(vjust = 0.45)) +
         labs(fill='Cuentas')+ theme_gray() + 
         theme(legend.position  = "bottom",     
               legend.direction = "horizontal",
               legend.title     = element_blank(),
               axis.title.y     = element_blank(),
               plot.title       = element_text(hjust = 0.5, size = 15, face= "bold"),
               axis.text.y      = element_text(size = 13),
               axis.text.x      = element_text(size = 13),
               legend.text      = element_text(size = 13),
               axis.line        = element_line(size=1, colour = "black"),
               panel.grid.major = element_blank(), 
               panel.grid.minor = element_blank(),
               panel.border     = element_blank(), 
               panel.background = element_blank())
               
   
ak <- ak + coord_flip() 
 

#devtools::install_github('Mikata-Project/ggthemr', force = TRUE)
#library(ggthemr)

ggthemr('light', type = 'inner')

ak <- ak +  scale_colour_ggthemr_d()
ak

Gráfico No9 : Barras negativas

  • Para trazar una línea vertical, paralela al eje X, escribimos geom_hline(yintercept=0)
  • scale_y_continuous(labels = scales::number_format(accuracy = 0.1, decimal.mark = ‘,’),breaks = seq(-8,8,4),limits=c(-8,8)): Esta opción permite setear al eje y, de tal manera, que presente un decimal, que el separador de decimal sea la coma, que la secuencia del eje vaya desde -8 a 8, con saltos de 4 puntos, y que el límite sea -8 y 8.
  • Para describir fuente al gráfico, detallamos la siguiente rutina:

theme(plot.caption = element_text(hjust = 0)) + labs(caption = “Fuente: FBI- BCE”)

ae <- ggplot(data=Data_II, aes(x=factor(Year), y = Crecimiento, fill= Países,
                           label = Crecimiento)) + geom_col(position = "dodge",
                                                            width = 0.7,
                                                            colour="gray2")

ae <- ae + ylab("") + xlab('')+scale_fill_brewer(palette="Pastel2")
                 
ae <- ae + geom_hline(yintercept=0)

ae <- ae +  theme(axis.line        = element_line(size=1, colour = "black"),
                  panel.grid.minor = element_blank(),
                  panel.border     = element_blank(),
                  panel.background = element_blank(),
                  text             = element_text(family="Times New Roman"),
                  axis.text.x      = element_text(colour="black", size = 14),
                  axis.text.y      = element_text(colour="black", size = 14),
                  axis.title       = element_text(size = 15))

ae <- ae + theme(legend.direction   = "horizontal",
                 legend.position    = 'bottom',
                 legend.title       = element_blank())

ae <- ae  + geom_text(position = position_dodge(width= 0.7), vjust= -0.28,
                      size=6,
                      aes(label=format(Crecimiento,
                                       big.mark = ".", decimal.mark= ",")))

ae <- ae + scale_x_discrete(labels = wrap_format(10))

ae <- ae + theme(legend.text = element_text(size = 17))  

ae <- ae + scale_y_continuous(labels = scales::number_format(accuracy = 0.1,
                                           decimal.mark = ','),
                              breaks = seq(-8,8,4),limits=c(-8,8))

ae <- ae + theme(plot.caption = element_text(hjust = 0)) + # set the left align here
            labs(caption = "Fuente: FBI- BCE")

ae

Para guardar el gráfico:

ggsave(“ae.png”,width = 22, height = 10, units = “cm”)

Gráfico No10 : Combinación de barras y líneas

#https://stackoverflow.com/questions/51456307/how-to-add-a-legend-for-the-secondary-axis-ggplot

DF = tibble(Periodo = seq(as.Date("2022-01-01"),as.Date("2022-12-01"), by = "month"), 
                B = c(100, 110, 105, 200, 210, 190, 180, 170, 165, 175, 140, 145),
                C = c(120, 130, 150, 170, 250, 160, 130, 120, 110, 130, 120, 170),
                D = c(1060, 1180, 1050, 2070, 2150, 1900, 1850, 1070, 1605, 1750, 1460, 1250))

DF_BAR <- reshape2::melt(DF, id.vars = "Periodo", measure.vars = c("B", "C", "D")) %>% 
          filter(variable != "D") 

DF_line <- DF %>% 
           select(Periodo, D)     
  • Base DF_BAR
Periodo variable value
2022-01-01 B 100
2022-02-01 B 110
2022-03-01 B 105
2022-04-01 B 200
2022-05-01 B 210
2022-06-01 B 190
2022-07-01 B 180
2022-08-01 B 170
2022-09-01 B 165
2022-10-01 B 175
2022-11-01 B 140
2022-12-01 B 145
2022-01-01 C 120
2022-02-01 C 130
2022-03-01 C 150
2022-04-01 C 170
2022-05-01 C 250
2022-06-01 C 160
2022-07-01 C 130
2022-08-01 C 120
2022-09-01 C 110
2022-10-01 C 130
2022-11-01 C 120
2022-12-01 C 170
  • Base DF_line
Periodo D
2022-01-01 1060
2022-02-01 1180
2022-03-01 1050
2022-04-01 2070
2022-05-01 2150
2022-06-01 1900
2022-07-01 1850
2022-08-01 1070
2022-09-01 1605
2022-10-01 1750
2022-11-01 1460
2022-12-01 1250
DF <- ggplot(data = DF_BAR, aes(x = Periodo, y = value, fill = variable)) + 
      geom_bar(stat = "identity", position = "dodge", colour="gray2") + 
      scale_fill_brewer(palette="Pastel2")+
      #theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
     theme(axis.text=element_text(size=9), 
     axis.title=element_text(size=14,face="bold")) +
     ylab("Bufalos") +
     geom_line(data = DF_line, aes(x = Periodo, y = (D)/10, group = 1), inherit.aes = FALSE,color="black", size=0.9) + 
     geom_point(data = DF_line, aes(x = Periodo, y = (D)/10, group = 1), inherit.aes = FALSE) +
     scale_y_continuous(sec.axis = sec_axis(~.*10, name = "Tauro"),expand= c(0,0)) 
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## i Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
DF <- DF + scale_x_date(date_labels = '%Y%-%b',
                        breaks = as.Date(c('2022-01-01',
                                           '2022-03-01',
                                           '2022-06-01',
                                           '2022-09-01',
                                           '2022-12-31')))

DF

Gráfico No11 : Combinación de barras y líneas: Caso III - Valores Negativos

CODIGO CUENTA Meses Cartera de Crédito Meses_II Variacion var_iii
14 CARTERA DE CRÉDITOS 2020-03-01 28.05 3 0.0000000 30.00000
14 CARTERA DE CRÉDITOS 2020-06-01 26.81 6 -0.0440356 15.02790
14 CARTERA DE CRÉDITOS 2020-09-01 26.54 9 -0.0103375 26.48525
14 CARTERA DE CRÉDITOS 2020-12-01 27.28 12 0.0279495 39.50284
14 CARTERA DE CRÉDITOS 2021-03-01 27.63 3 0.0129515 34.40352
14 CARTERA DE CRÉDITOS 2021-06-01 28.33 6 0.0252887 38.59817
14 CARTERA DE CRÉDITOS 2021-09-01 29.83 9 0.0527787 47.94476
14 CARTERA DE CRÉDITOS 2021-12-01 31.33 12 0.0504042 47.13742
14 CARTERA DE CRÉDITOS 2022-03-01 32.49 3 0.0370309 42.59051
14 CARTERA DE CRÉDITOS 2022-06-01 33.60 6 0.0342396 41.64147
af <- ggplot() + 
      geom_bar(data=Cartera, aes(x=Meses, y = `Cartera de Crédito`),
               stat = "identity",colour="gray7", fill="khaki4") +     
       theme_stata()

af <- af + scale_x_date(date_labels = '%Y%-%b',
                          breaks    = as.Date(c( '2020-03-01',
                                                 '2020-06-01',
                                                 '2020-09-01',
                                                 '2020-12-01',
                                                 '2021-03-01',
                                                 '2021-06-01',
                                                 '2021-09-01',
                                                 '2021-12-01',
                                                 '2022-03-01',
                                                 '2022-06-01'))) 
  

af <- af + geom_line(data=Cartera,mapping = aes(x = Meses, y = Variacion*340+30), 
                                                color="black", size=0.6,linetype = 1)+
           geom_point(data=Cartera,mapping = aes(x = Meses, y = Variacion*340+30), 
                                              color="darkblue", size=1)+
           scale_y_continuous(expand     = c(0,0),
                              sec.axis   = ggplot2::sec_axis(~(.-30)/340, 
                                    name = "Variación Porcentual",
                                labels   = scales::label_percent()))
af

Histogramas

Arrancamos con un histograma básico, el cual se generó mediante la siguiente forma: Norm <- rnorm(10000))

color = “black”: Indica el color de la línea de cada barra, en este caso se elige el colot negro.
fill: El color de las barras.

ba <- ggplot(data=Norm, aes(x= data))  
ba <- ba  + geom_histogram(color = "black", fill = "#E7B800") + scale_y_continuous(expand = c(0,0))
ba
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

Histograma: Incluir línea vertical del promedio de la distribución

geom_vline: Permite crear una línea vertical, en la cual señala el promedio de la distribución

geom_text: Permite detallar con las coordenadas específicas, el promedio de la serie.

bb <- ggplot(data=Norm, aes(x= data))  
bb <- bb  + geom_histogram(color = "black", fill = "azure3") + scale_y_continuous(expand = c(0,0)) +
       geom_vline(aes(xintercept = mean(data)), col = "blue", linetype="dashed", size=1) +
       geom_text(x = 1, y = 780, label = paste("Mean", round(mean(Norm$data, digits = 2))
                                                       , sep = '\n'), color = "black")
                                                                    
bb
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

Funciones

Histogramas: Caso I

En este apartado revisaremos breves aspectos de la aplicación de funciones que nos permitirá generar graficos de forma automatizada. En este caso haremos una gráfico de histograma, por cada una de las especies: virginica, versicolor, setosa, tomando como variable x: Sepal. Length

Dattos <- as.data.table(iris)
Figuras <- split(Dattos, Dattos$Species)

for (i in seq(length(Figuras))) {
      ql <- ggplot(data=Figuras[[i]], aes(x= Sepal.Length)) 
      ql <- ql + geom_histogram(color = "black", fill = "lightskyblue1", binwidth = 0.5)
      ql <- ql + scale_y_continuous(expand = c(0,0)) + theme_stata()    
      ql <- ql + ggtitle(sprintf("Histograma de %s",names(Figuras)[i])) 
      ql <- ql + ylab("Frecuencia") + xlab("Sepal.Length") 
      print(ql)
}

Histogramas: Caso II.

En este gráfico se incorpora tanto el promedio como la desviación estándar.

dibujos_qq2 <- list()  ### Actualizar R Markdown

for (i in seq(length(Lista_Prueba_A))) {
  # Filter and calculate mean and sd for each BoM group
  df <- Lista_Prueba_A[[i]] %>% 
        dplyr::filter(Dummy > 0) %>%
        mutate(Saldos=Saldos/1000000)%>%
        group_by(BoM) %>%
        summarise(mean_Saldos = mean(Saldos, na.rm = TRUE),
                  sd_Saldos = sd(Saldos, na.rm = TRUE),
                  .groups = "drop")
  
  # Add the statistics back to the data for plotting
  plot_data <- Lista_Prueba_A[[i]] %>%
               dplyr::filter(Dummy > 0) %>%
               left_join(df, by = "BoM")
  
  # Create the plot
  qq2 <-  ggplot(plot_data, aes(x = Saldos)) +
          geom_histogram(bins = 20, fill = "pink", colour = "#CC3300") +
          xlab("Periodicidad: Mensual") +
          facet_wrap(~BoM) +
          geom_text(aes(
              label = paste0("Mean: ", round(mean_Saldos, 2), 
                             "\nSD: ", round(sd_Saldos, 2))
            ),
            x = Inf, y = Inf, 
            hjust = 1.1, vjust = 1.1,
            inherit.aes = FALSE
          )+  scale_x_continuous(
           labels = scales::label_number(scale = 1e-6, suffix = "M"),  # Convert to millions
           breaks = scales::pretty_breaks(n = 5)
       ) + theme_minimal()
  
  # Print and save the plot
  print(i)
  print(qq2)
  dibujos_qq2[[i]] <- qq2
}
## [1] 1

## [1] 2

Pie-Chart:

En este espacio, expondremos como realizar un gráfico de pastel (pie-chart), automatizándolo de tal manera, que se realice un gráfico por género (mujer- hombre) por tipo de examen (A & B) y por examen (MT- Final).

Resultado Examenes
Exam Gender Exam Type Points
Final M B 40
Final F B 32
Final F B 60
Final M B 64
Final M B 56
Final M B 28
Final F A 56
Final M B 60
Final M B 44
Final F A 44
Final F B 60
Final F B 72
Final F A 56
Final F B 56
Final M B 48
Final F B 36
Final F B 24
Final F B 48
Final F B 72
Final F A 60
Final F A 76
Final M B 68
Final M A 60
Final M B 44
Final M B 64
Fuente: https://data.mendeley.com/datasets/49k3rnrwkk/1
sexo <- function(b, Gender){
  
  tabla<-b[,.(num=.N,media=mean(Points)),by=.(Gender,`Exam Type`)]
  
  if(Gender == 'F'){
    tabla<-tabla[Gender=='F']
    tabla[,Composicion:=round(100*num/sum(num),2)]
    tabla<-tabla[order(num)]
    

    HM <-  ggplot(data=tabla, aes(x='', y=Composicion, fill=`Exam Type`)) +
      
      geom_bar(width=1, stat="identity") +
      
      labs(x=NULL,y=NULL) +
       geom_text(aes(label = paste(format(tabla$Composicion, big.mark = '.', 
                              decimal.mark = ',', format = "f",
                              scientific   = FALSE ), '%')), size=5, colour = 'black', 
        position = position_stack(vjust = 0.5)) +
      theme_minimal() +
      theme(axis.ticks = element_blank(),
            axis.text.x = element_blank(),
            axis.text.y = element_blank(),
            axis.title = element_blank(),
            axis.line.x = element_blank(),
            axis.line.y = element_blank(),
            plot.margin=unit(c(1,1,1,1), "cm")) +
      coord_polar(theta = 'y') + 
      theme_void()
    ggsave( HM,height=2, width =4,file = paste(getwd(),'/sexo_Mujer', '.png', sep = '' ))  
    
} else{
    
    tabla<-tabla[Gender=='M']
    tabla[,Composicion:=round(100*num/sum(num),2)]
    tabla<-tabla[order(num)]
  
    HM <-   ggplot(data=tabla, aes(x='', y=Composicion, fill=`Exam Type`)) +
                  geom_bar(width=1, stat="identity") +
                          labs(x=NULL,y=NULL) +
        geom_text(aes(label = paste(format( tabla$Composicion, big.mark = '.', 
                              decimal.mark = ',', format = "f",
                              scientific = FALSE ), '%')), size=4.5, colour = 'black', 
        position = position_stack(vjust = 0.5)) +
      theme_minimal() +
      theme(axis.ticks = element_blank(),
            axis.text.x = element_blank(),
            axis.text.y = element_blank(),
            axis.title = element_blank(),
            axis.line.x = element_blank(),
            axis.line.y = element_blank(),
            plot.margin=unit(c(1,1,1,1), "cm")) +
      coord_polar(theta = 'y') + 
      theme_void()
      theme_stata()
    ggsave( HM,height=2, width =4,file = paste(getwd(),'/sexo_Hombre', '.png', sep = '' ))  
    
  }
}

# Activar Fórmula

wdinf <-paste(getwd(),sep='')
setwd(wdinf)
dbg <-FALSE
quiet<-TRUE

informe_nombre<-'INFORME'

#rm(i)

Tipo_examenes <- unique(dataset_one$Exam)

for(i in 1:length(Tipo_examenes) ){

data_one <- dataset_one[Exam == Tipo_examenes[i],]
soporte  <- Tipo_examenes[i]

sexo(data_one, 'F')  #ok
sexo(data_one, 'M') #

informe.nom <- paste('INFORME_',soporte, sep = '' )
infolder.graficos<-paste(informe.nom, '/GRAPH/', sep = '' )

if (file.exists(informe.nom)) {
  unlink(informe.nom, recursive = TRUE )
}
dir.create(informe.nom, recursive = TRUE ) 
dir.create(infolder.graficos, recursive = TRUE ) 

fls_png<-c('sexo_Mujer.png','sexo_Hombre.png')
 
file.copy(fls_png, paste(informe.nom, '/', fls_png, sep = '' ), overwrite = TRUE  )

setwd(paste( wdinf,'/',informe.nom, sep = '' ) )
setwd(wdinf)
}

Invitamos al lector que aplique la rutina antes descrita y pueda constatar como los gráficos programados se generan a las carpetas creadas para el efecto.

Pie-Chart: scales:: percentage

kob_II <- kable(kob)%>%
          kable_styling(bootstrap_options = "striped", font_size = 12, full_width = F) %>%
          kable_classic(full_width = F, html_font = "Cambria")%>%
          row_spec(0, color = "white", background = "#6897BB", align = "left", bold= T) 

kob_II
File Book Composición
Batman 150 0.5681818
Robin 114 0.4318182
  • Con la opción scales::percent, es factible transformar el formato de los números en porcentajes. Accuracy permite establecer el número de decimales requerido.
mycols = c('firebrick4', 'dodgerblue4')

II <- ggplot(kob, aes(x = "", y = Composición, fill = File)) +
      geom_col(color = "black", size=1.2) +
      geom_text(position = position_stack(vjust = 0.5), size=8,color = "white",
                aes(label= scales::percent(Composición, accuracy = 0.01 ,suffix = "%",
                                           big.mark = "",
                                           decimal.mark = ",")))+
      coord_polar(theta = "y") +
      scale_fill_manual(values = mycols) + theme_void()
     
   
II <- II + theme(legend.title     = element_blank())
 
II <- II + theme(legend.text = element_text(size = 20))

II

Gráfico de Línea

BB <- ggplot(GRAPH_1) + geom_line(aes(x = Meses, y = `Cartera de Créditos`
                                      , colour = 'Cartera de Créditos'), size=1)+
      geom_line(aes(x = Meses,y = `Obligaciones con el Público`, 
                colour = 'Obligaciones con el Público'), size=1) + 
     scale_color_manual(values = c("blue4", "firebrick4"))+
     labs(y='',
          x= '',
          colour='')+
  theme_economist()+
  ggtitle('Cartera de créditos - Obligaciones con el Público',
          subtitle = 'En millones USD')+ 
  theme(legend.position  = 'bottom',
        legend.direction = 'horizontal',
        legend.title     = element_blank())

BB <- BB + scale_x_date(date_labels = '%Y%-%b',
                        breaks = as.Date(c('2016-12-31',
                                           '2017-12-31',
                                           '2018-12-31',
                                           '2019-12-31',
                                           '2020-12-31',
                                           '2021-07-31')))

BB <- BB + theme(axis.text.x = element_text(size = 10))  

BB

Doble Eje

AA <- ggplot(GRAPH_1) + geom_line(aes(x = Meses, y = `Cartera de Créditos`
                                      , colour = 'Cartera de Créditos'), size=1)+
     geom_line(aes(x = Meses,y = `Obligaciones con el Público`, 
                   colour = 'Obligaciones con el Público'), size=1) + 
     scale_y_continuous(sec.axis = sec_axis(~.*5, name= 'Obligaciones con el Público'))+
     scale_color_manual(values = c("blue4", "firebrick4"))+
     labs(y='Cartera de Créditos',
          x= 'Meses',
          colour='Cuentas')+
     theme_economist()+
     ggtitle('Cartera de créditos - Obligaciones con el Público 
              En millones USD')+
     theme(plot.title = element_text(hjust = 0.5),
           legend.position  = 'bottom',
           legend.direction = 'horizontal',
           legend.title     = element_blank())

AA <- AA + scale_x_date(date_labels = '%Y%-%b',
                        breaks = as.Date(c('2016-07-31',
                                           '2017-07-31',
                                           '2018-07-31',
                                           '2019-07-31',
                                           '2020-07-31',
                                           '2021-07-31')))

AA

Combinación puntos y líneas

AF <- ggplot(Mundial, aes(x=Fecha, y=Importaciones, group=Países))+
      geom_line(aes(linetype=Países, color=Países),size=0.8)+
      geom_point(aes(color=Países))+
      scale_color_manual(values = c("#00008B","#800000"))+ theme_classic()

AF

Gráfico de puntos

Para este gráfico de puntos, se apoyará en la libreria ggrepel, que permite etiquetar a las variables.

Puntos <- ggplot(Todos_Box_A) +
    scale_fill_manual(values = c("1"="#36648B", '2'="#8B668B",
                                 "3"="brown"))+
    scale_color_manual(values = c("1"="#36648B", '2'="#8B668B",
                                  "3"="brown"))+
    labs(x="Libertad",y="Paz")+
    geom_point(size=3,
               aes(x = Libertad, y = Paz,
                   fill =factor(Cluster),
                   color=factor(Cluster)))+
    geom_label_repel(aes(Libertad, Paz,
                         label = ID, fill = factor(Cluster)),
                     fontface = 'bold', color = 'white',
                     max.overlaps = 20,
                     box.padding = unit(0.25, 'lines'),
                     point.padding = unit(0.5, 'lines'))+
        TEMASA +theme(legend.text = element_text(size = 15))+
    guides(fill = guide_legend(override.aes = aes(color = NA)))

Puntos

Libreria cowplot

Esta libreria permite colocar dos gráficos (objetos), en un mismo cuadrante

plot_grid(ab, abl, labels = c('Modelo I', 'Modelo II'),
          label_size = 10)

Cuadrantes

filla <- c("aquamarine4","chocolate4","yellow2", "brown4", "darkmagenta",
           "thistle2", "skyblue1", "slategray1", "cyan2", "tan")

akj <- ggplot(data = Actividades, aes(y=Proporcion, x=Año, fill=factor(`Actividad económica`)))+
        geom_bar(stat= "identity",position="stack" ,width = 0.6,colour="gray2")+ 
        guides(fill = guide_legend(reverse = TRUE)) +
        xlab('Años')+ ylab('Porcentajes[%]') + 
        scale_y_continuous(expand = c(0,0))+geom_text(aes(Año, label=paste0(Proporcion,'%')),
                                                      colour= 'black', position= position_stack(vjust = 0.5)) 

akj <- akj +labs(fill= 'Actividad económica')+ theme_stata()+
        theme(legend.position = "bottom", legend.direction = "horizontal",
              legend.title    = element_blank())+ scale_fill_manual(values = filla)

akj <- akj + scale_x_continuous(breaks=seq(2015, 2020, 1))

akj <- akj + facet_wrap(~PROVINCIA, scales = "free_y") 
akj <- akj + facet_wrap(~PROVINCIA, scales = "free_x") 

akj <- akj + labs(caption    = "Fuente:BCE") +
              theme(plot.caption       =  element_text(size = 9),
                    legend.position    = 'bottom',
                    legend.title       =  element_blank(),
                    axis.title.x       =  element_blank(),
                    axis.title.y       =  element_blank(),
                    text = element_text(size = 14))


akj

Caso I: geom_line

TEMAD <- theme(axis.line   = element_line(size=1, colour = "black"),
              plot.title = element_text(hjust=0.5, size =16, face = "bold"),
              legend.text = element_text(size = 30),
              plot.caption       =  element_text(size = 8),
              legend.position    = 'none',
              legend.title       = element_blank(),
              axis.text.x        = element_text(size = 12),
              axis.text.y        = element_text(size = 12),
              text               = element_text(size = 12),
              panel.grid.major   = element_blank(),
              panel.grid.minor   = element_blank(),
              panel.border       = element_blank(),
              panel.background   = element_blank())

CC <- ggplot(data = Decil_10_A,
             mapping = aes(y = Indicador, x = Años , colour = 'Indicador',group = 1)) +
        scale_color_manual(values = c("navy"))+
        labs(y='Five [%]',
             x= '',
             colour='')+
            geom_line(size=1) +
            geom_point(size=1.5) +TEMAD

CC <- CC + facet_wrap(~Ciudades, scales = "free_y")
CC <- CC + facet_wrap(~Ciudades, scales = "free_x") + 
           theme(strip.text.x = element_text(size = 15))

CC <- CC +  geom_label_repel(aes(label = format(Indicador,
                                               big.mark = ".", decimal.mark= ",")),
                      data = Decil_10_A %>% filter(Años %in% c('2016', '2019')),
                      nudge_x = 0.15,
                      size = 4)

CC <- CC + theme(strip.text=element_text(face='bold', size=14,color='white'),
                 strip.background=element_rect(fill='navy'))

CC

Caso II: Gráfico y tabla

Para la creación de un gráfico y tabla de forma simultáneamente, invocaremos a la library(ggpubr)

G1b <- ggbarplot(Centros, "Año", "Centros",
                 fill = 'Unidades', 
                 color = "black", palette = "Paired",
                 label = TRUE, position = position_dodge(0.7)) + scale_y_continuous(limits = c(0,2500), 
                                                                                    expand = c(0,0))

G1b <- G1b + theme(legend.position="bottom", legend.direction="horizontal",
                   legend.title = element_blank()) +labs(x="Años", y="Refugios")

#G1b


CCENTROS_A <- Centros       %>%
              group_by(Año) %>%
              summarise('Número de Centros'=sum(Centros))

table_two <- ggtexttable(CCENTROS_A, rows = NULL,
                         theme = ttheme(base_size = 15,
                                        colnames.style = colnames_style(color = "white", 
                                                                        fill = "darkblue")))

GGGA <- ggarrange(G1b, table_two,
                  ncol = 2, nrow=1,
                  #heights = c(0.8,0.3),
                  widths = c(0.8,0.4))
GGGA

Box Plot

Función

FF <- ggplot(data=Tango, aes(x=Concepto ,y=Numero))

FF <- FF + geom_boxplot()+
      stat_summary(
        aes(label = round(stat(y), 1)),
        geom = "text", 
        fun  = function(y) { o <- boxplot.stats(y)$out; if(length(o) == 0) NA else o },
        hjust = -1
      )
FF
## Warning: `stat(y)` was deprecated in ggplot2 3.4.0.
## i Please use `after_stat(y)` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
## Warning: Removed 1 rows containing missing values (`geom_text()`).

set.seed(349)

cooll <- data.frame(Letra  = sample(LETTERS[1:3], 25, TRUE), 
                    number = sample (1:100, 25, replace = TRUE),
                    Chair  = sample (1:100, 25, replace = TRUE),
                    Year   = sample (2020:2021, 25, replace = TRUE))

cooll$Letra <- as.factor(cooll$Letra)

head(cooll,5)
##   Letra number Chair Year
## 1     B     24    40 2020
## 2     A     11    42 2020
## 3     A     85    97 2021
## 4     A     76    57 2020
## 5     B     74    60 2021
fill <- "#4271AE"
line <- "#1F3552"

Planta <-  ggplot(cooll, aes(x = Letra, y = number)) +
                  geom_boxplot(fill  = fill, colour = line)+
            theme(axis.line          = element_line(size=1, colour = "black"),
                    panel.grid.minor = element_blank(),
                    panel.border     = element_blank(),
                    panel.background = element_blank(),
                    #text             = element_text(family="mono"),
                    axis.text.x      = element_text(colour="black", size = 14),
                    axis.text.y      = element_text(colour="black", size = 14),
                    axis.title       = element_text(size = 15))
Planta

Automatización: Caso I Box Plot

Automatización a travéz de un vector de variables

response <- names(cooll)[2:3]
response <- purrr::set_names(response)

En este caso generamos un gráfico de cajas, por la variable letra y chair

fill <- "firebrick"
line <- "#1F3552"

scatter_fun = function(x, y) {
     ggplot(cooll, aes(x = .data[[x]], y = .data[[y]]) ) +                         geom_boxplot(fill  = fill, colour = line, width=0.4) +theme_bw()
}

#scatter_fun(x = "Letra", y = "Chair")

elev_plots <- map(response, ~ scatter_fun("Letra",.x))
elev_plots
## $number

## 
## $Chair

Automatización a travéz de la variable number, por año

Ahora en cambio, automatizaremos un gráfico por la variable number y , desagregado por Year (2020, 2021)

filla <- "blue"
line <- "#1F3552"

TTEMAS <- theme(axis.line            = element_line(size=1, colour = "black"),
                    panel.grid.minor = element_blank(),
                    panel.border     = element_blank(),
                    panel.background = element_blank(),
                    #text             = element_text(family="mono"),
                    axis.text.x      = element_text(colour="black", size = 14),
                    axis.text.y      = element_text(colour="black", size = 14),
                    axis.title       = element_text(size = 15))


ListaGrupos = sort(unique(cooll$Year)) #En lista los años 

dibujos <- list()
for (i in seq_along(ListaGrupos)) {  #Para cada uno de los valores de la lista...
     Todos <-
        ggplot(subset(cooll, cooll$Year==ListaGrupos[i]),
               aes(x = Letra, y = number)) +
                 geom_boxplot(fill  = filla, colour = line, width=0.4) +
                 TTEMAS +
       ggtitle(paste("Number", ListaGrupos[i]))
print(i)
print (Todos) #Mostrar gráficos en la pantalla
dibujos[[i]] <- Todos
}
## [1] 1

## [1] 2

names(dibujos) <- c('2020', '2021')

Con esta rutian, podemos automatizar los gráficos por año considerando las variables Chair y number

relleno <- "cyan3"
line <- "#1F3552"

Year_JJ <- cooll %>% 
           arrange(Year)%>%
           group_by(Year) %>% 
           nest()%>%
           mutate(Sillas = map(.x = data, 
                          ~ ggplot(data = .x) + 
                            aes(x = Letra,
                                y = Chair) +
                  geom_boxplot(fill  = relleno, colour = line)+
                    TTEMAS),
                  Numero = map(.x = data, 
                          ~ ggplot(data = .x) + 
                            aes(x = Letra,
                                y = number) +
                  geom_boxplot(fill  = 'coral', colour = line)+
                    TTEMAS))

HH <- plot_grid(Year_JJ[[3]][[1]],Year_JJ[[3]][[2]], Year_JJ[[4]][[1]],Year_JJ[[4]][[2]] ,labels = c('Chair 2020', 'Chair 2021', 'Number 2020', 'Number 2021'), label_size = 8, hjust = -1.4)
HH

Iterar entre dos listas

load("D:/Documentos/Estadisticos/R/R_studio/Markdown/Ggplot/Graph_6.RData")

sector_names <- c("Ecuador",
                  "Colombia")

Fecha_A <- ymd("2024-10-20")

Xgen0 <- Xgen0 %>%
         map(~mutate(.x,TSUMBoM=TSUMBoM/-11))  

TABoMSIM_AA <- TABoMSIM_AA %>%
               map(~mutate(.x,CVaR=CVaR/1.5))

dibujos_VI <- map(seq(length(Xgen0)), function(i) {
  
  # Use the individual data frame from the list for plotting
  data_frame <- Xgen0[[i]]
  
  # Create the plot
  q6 <- ggplot(data_frame, aes(x = TSUMBoM)) + 
                geom_histogram(aes(y = after_stat(density)), colour = 1, fill = "white", binwidth = 100) +
                geom_density(lwd = 1, colour = 4, fill = 4, alpha = 0.25) +
                annotate("text", x = TABoMSIM_AA[[i]]$CVaR - 80, y = 0.000075, 
                         label = paste0("≈ CVaR  AL ", " (", (100 - (100 * as.double(TABoMSIM_AA[[i]]$`Prob(%)`))),"%", ") : ", " USD ", abs(TABoMSIM_AA[[i]]$CVaR)),
                         size = 4, color = "Black", angle = 90, hjust = 0) +
                geom_vline(xintercept = TABoMSIM_AA[[i]]$CVaR, colour = "navy", size = 1, linetype = "dashed") +
                xlab("Trimestral") + 
                ylab("Pesos Colombiano ") +
                labs(title = paste0("Países: ", sector_names[i]),
                     subtitle = "1998-2012",
                     caption = "Fuente: Amigos Anonimos") +
                scale_y_continuous(expand = c(0, 0)) +
                theme(plot.title = element_text(size = 10, hjust = 0.5),
                      plot.subtitle = element_text(size = 9, hjust = 0.5, vjust = -1),
                      plot.caption = element_text(size = 8))
  
q6
})

#Save graph
names(dibujos_VI) <- sector_names

combined_plot_VI <- grid.arrange(dibujos_VI[[1]], dibujos_VI[[2]], ncol = 2)

# Save the combined graph
ggsave(
  filename = paste0("Graph_IV_", Fecha_A, ".png"),  # File name with date
  plot = combined_plot_VI,                            # The ggplot object to save
  width = 12,                                      # Width of the image (default in inches)
  height = 9,                                      # Height of the image (default in inches)
  units = "in",                                    # You can set this to "cm" or "mm"
  dpi  = 500,                                        # DPI for resolution (optional, 300 is high quality)
  path = "Graph_pol")