Autor: Álvaro Alonso Fernández
Departamento de Ciencias de la Vida
Universidad de Alcalá (España)


Vamos a realizar un gráfico de violín


1 Objetivo

Queremos realizar un gráfico de violín. Es un gráfico adecuado para mostrar las densidades de probabilidades que toman nuestros datos. Nos da información sobre que valores se “repiten” más en nuestros datos. Es bueno si lo combinamos con medidas de tendencia central y dispersión, como un boxplot.

2 Nuestros datos

Cargamos nuestro dataframe:

setwd(dir = "F:/R/MARKDOWN-ggplot2/violin")
datos<-read.table("violin.csv", sep = ";", header = TRUE, dec = ".")
datos
##    city heigh age
## 1     A   175  25
## 2     A   184  20
## 3     A   175  24
## 4     A   180  26
## 5     A   175  21
## 6     A   185  19
## 7     A   175  18
## 8     A   181  19
## 9     B   169  22
## 10    B   168  28
## 11    B   168  29
## 12    B   171  31
## 13    B   171  32
## 14    B   174  33
## 15    B   168  29
## 16    B   171  28
## 17    C   166  31
## 18    C   165  30
## 19    C   163  24
## 20    C   163  33
## 21    C   166  34
## 22    C   165  35
## 23    C   163  35
## 24    C   163  34
## 25    D   189  39
## 26    D   188  33
## 27    D   188  35
## 28    D   187  38
## 29    D   189  41
## 30    D   192  45
## 31    D   190  42
## 32    D   187  49
str(datos)
## 'data.frame':    32 obs. of  3 variables:
##  $ city : chr  "A" "A" "A" "A" ...
##  $ heigh: int  175 184 175 180 175 185 175 181 169 168 ...
##  $ age  : int  25 20 24 26 21 19 18 19 22 28 ...

Vamos a representar city frente a age. Es decir, tenemos una variable categórica y una dependiente cuantitativa. Ahora cargamos la libreria de ggplo2:

library(ggplot2)
## Warning: replacing previous import 'lifecycle::last_warnings' by
## 'rlang::last_warnings' when loading 'tibble'
## Warning: replacing previous import 'lifecycle::last_warnings' by
## 'rlang::last_warnings' when loading 'pillar'

3 Lo más sencillo

Vamos a hacer el gráfico más sencillo posible:

ggplot(datos, aes(x = city, y = age, fill = city)) +
  geom_violin(alpha = 0.5) +
  theme(legend.position = "none")

4 Incluimos las observaciones

Para ello se añade geom_point():

ggplot(datos, aes(x = city, y = age, fill = city)) +
  geom_violin(alpha = 0.5) +
  geom_point() +
  theme(legend.position = "none")

5 Incluimos un boxplot

Para ello se añade geom_boxplot(width = 0.2) y con width seleccionamos la anchura del boxplot:

ggplot(datos, aes(x = city, y = age, fill = city)) +
  geom_violin(alpha = 0.5) +
   theme(legend.position = "none")+
  geom_boxplot(width = 0.2)

6 Incluimos la media

Podemos indicar por medio de un punto el valor medio para cada una de nuestras ciudades. Para ello se añade stat_summary y con la función mean y con geom="point indicamos que sea un punto, en este caso negro:

ggplot(datos, aes(x = city, y = age, fill = city)) +
  geom_violin(alpha = 0.5) +
  theme(legend.position = "none")+
stat_summary(fun = "mean",
             geom = "point",
             color = "black")

7 Incluimos la media con una línea

Podemos indicar por medio de una línea la media, en este caso verde oscura:

ggplot(datos, aes(x = city, y = age, fill = city)) +
  geom_violin(alpha = 0.5) +
  theme(legend.position = "none")+
stat_summary(fun = "mean",
              geom = "crossbar", 
             width = 0.25,
             color = "darkgreen")

8 Incluimos el intervalo de confianza de la media

Para ello hay que utilizar la función fun.data = "mean_cl_boot":

ggplot(datos, aes(x = city, y = age, fill = city)) +
  geom_violin(alpha = 0.5) +
  theme(legend.position = "none")+
stat_summary(fun.data = "mean_cl_boot", geom = "crossbar",
             colour = "black", width = 0.2)

9 Incluimos la media y la mediana

Para ello repetimos lo mismo que hemos hecho con la media pero cambiando fun="median". Además paso la figura a un objeto llamado a para facilitar los siguientes pasos del tutorial:

ggplot(datos, aes(x = city, y = age, fill = city)) +
  geom_violin(alpha = 0.5) +
  theme(legend.position = "none")+
stat_summary(fun = "mean",
            geom = "point",
            color = "black") +
  stat_summary(fun = "median",
               geom = "point",color = "red")

a<-ggplot(datos, aes(x = city, y = age, fill = city)) +
  geom_violin(alpha = 0.5) +
  theme(legend.position = "none")+
stat_summary(fun = "mean",
            geom = "point",
            color = "black") +
  stat_summary(fun = "median",
               geom = "point",color = "red")

10 Mejorar fondo

Ahora vamos a cambiar el fondo de nuestra figura. Hay varias opciones theme_classic(), theme_minimal(), theme_light(), etc. Aquí un resumen:



Vamos a ver como quedan nuestras figuras con las seis opciones disponibles. Aplicamos la libreria patchwork que nos permite agrupar las figuras en una sola:

library(patchwork)

grA<- a + theme_classic()+ theme(legend.position = "none")

grB<- a + theme_minimal()+ theme(legend.position = "none")

grC<- a + theme_light()+ theme(legend.position = "none")

grD<- a + theme_dark()+ theme(legend.position = "none")

grE<- a + theme_gray()+ theme(legend.position = "none")

grF<- a + theme_linedraw()+ theme(legend.position = "none")

(grA | grB | grC ) / (grD | grE | grF )

11 Mejorar color

Ahora vamos a cambiar los colores de nuestra figura. Hay varias opciones:



Vamos a ver como quedan algunos ejemplos:

library(patchwork)

grA<- a + scale_fill_brewer(palette="Reds")

grB<- a + scale_fill_brewer(palette="Set1")

grC<- a + scale_fill_brewer(palette="Spectral")

grD<- a + scale_fill_brewer(palette="Greys")

grE<- a + scale_fill_brewer(palette="BuPu")

grF<- a + scale_fill_brewer(palette="PuBu")

(grA | grB | grC ) / (grD | grE | grF )


!!Ya somos unos virtuosos “del violín”¡¡


12 CRÉDITOS

Álvaro Alonso Fernández

Departamento de Ciencias de la Vida

Universidad de Alcalá (España)