Questa è una guida introduttiva alla Data Visualization in R con ggplot2

Utilizzeremo diversi dataset tutti open source
library(tidyverse)

data("mpg")
head(mpg)
# A tibble: 6 x 11
  manufacturer model displ  year   cyl      trans   drv   cty   hwy    fl
         <chr> <chr> <dbl> <int> <int>      <chr> <chr> <int> <int> <chr>
1         audi    a4   1.8  1999     4   auto(l5)     f    18    29     p
2         audi    a4   1.8  1999     4 manual(m5)     f    21    29     p
3         audi    a4   2.0  2008     4 manual(m6)     f    20    31     p
4         audi    a4   2.0  2008     4   auto(av)     f    21    30     p
5         audi    a4   2.8  1999     6   auto(l5)     f    16    26     p
6         audi    a4   2.8  1999     6 manual(m5)     f    18    26     p
# ... with 1 more variables: class <chr>
# displ è la grandezza del motore in litri
# cyl sono i cilindri
# hwy è l'efficienza di consumo in autostrata
# cty è l'efficienza di consumo in città

Scatterplot

ggplot(data = mpg) +
    geom_point(mapping = aes(x = displ, y = hwy))

è possibile modificare la grandezza (SIZE), la forma (SHAPE), il colore (COLOR), la trasparenza (ALPHA) dei punti
# colore
ggplot(mpg) + 
    geom_point(aes(x = displ, y = hwy, color = class))

ggplot(mpg) +
    geom_point(mapping = aes(x = displ, y = hwy), color = "red")

# grandezza
ggplot(mpg) +
    geom_point(mapping = aes(x = displ, y = hwy, size = class))

# trasparenza
ggplot(mpg) +
    geom_point(mapping = aes(x = displ, y = hwy, alpha = class))

# forma
ggplot(mpg) +
    geom_point(mapping = aes(x = displ, y = hwy, shape = class))

##### è possibile modificare forma e colore inisieme

ggplot(mpg) +
    geom_point(mapping = aes(x = displ, y = hwy, color = cyl, shape = drv))

# impostare valori logici nell' aesthetics COLOR
ggplot(mpg) + 
    geom_point(aes(x = displ, y = hwy, color = displ < 5))

è possibile anche creare diversi pannelli

ggplot(data = mpg) +
    geom_point(mapping = aes(x = displ, y = hwy)) +
    facet_grid(. ~ cyl)

# è possibile sezionare la combinazione tra due variabili
ggplot(data = mpg) +
    geom_point(mapping = aes(x = displ, y = hwy)) +
    facet_grid(drv ~ class)

# Disposizione orizzontale
ggplot(data = mpg) +
    geom_point(mapping = aes(x = displ, y = hwy)) +
    facet_grid(drv ~ .) 

# Geom “smooth”

ggplot(data = mpg) + 
    geom_smooth(mapping = aes(x = displ, y = hwy)) + geom_point(aes(x = displ, y = hwy))

in grigio l’intervallo di confidenza

è possibile impostare una categoria gruppo

1

ggplot(data = mpg) +
    geom_smooth(mapping = aes(x = displ, y = hwy), se = FALSE)

2

ggplot(data = mpg) +
    geom_smooth(mapping = aes(x = displ, y = hwy, color = drv), se = FALSE)

3

ggplot(data = mpg) + 
    geom_smooth(mapping = aes(x = displ, y = hwy, linetype = drv, color = drv), se = FALSE) +
    geom_point(mapping = aes(x = displ, y = hwy, color = drv))

è possibile impostare le aesthetics direttamente all’interno della funzione ggplot. In questo modo le impostazioni verranno applicate a tutti i “geom” che inserirete
ggplot(data = mpg, aes(x = displ, y = hwy)) + # si applica ad ogni geom 
    geom_point(mapping = aes(color = class)) + # solo gli assi però
    geom_smooth(se = FALSE)

# possiamo scegliere dei filtri per ogni geom

ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) +
    geom_point(mapping = aes(color = class)) +
    geom_smooth(data = filter(mpg, class == "subcompact"),
                se = FALSE) # filtro per lo smooth

# color applicato solo a geom point
ggplot(mpg, aes(x = displ,y = hwy)) + 
    geom_point(aes(color = drv)) +
    geom_smooth(se = FALSE)

ggplot(mpg, aes(x = displ,y = hwy)) + # color solo ai point
    geom_point(aes(color = drv)) + # linetype ai geom
    geom_smooth(aes(linetype = drv), se = FALSE)

è possibile applicare trasformazioni statistiche ai dati

demo <- tribble(
     ~a,     ~b,
    "bar_1", 20,
    "bar_2", 30,
    "bar_3", 40
)

ggplot(data = demo) +
    geom_bar(mapping = aes(x = a, y = b), stat = "identity")

ggplot(data = diamonds) +
    stat_summary(mapping = aes(x = cut, y = depth),
                 fun.ymin = min,
                 fun.ymax = max,
                 fun.y = median)

ggplot(diamonds, aes(price, ..density.., colour = cut)) +
    geom_freqpoly(binwidth = 500)

df <- data.frame(trt = c("a", "b", "c"), outcome = c(2.3, 1.9, 3.2))
ggplot(df, aes(trt, outcome)) +
    geom_col()

# position adjustments and color

ggplot(data = diamonds) +
    geom_bar(mapping = aes(x = cut, fill = cut))

# se inseriamo un'altra variabile le barre si staccano da sole
ggplot(data = diamonds) +
    geom_bar(mapping = aes(x = cut, fill = clarity)) 

ggplot(data = diamonds) +
    geom_bar(mapping = aes(x = cut, fill = clarity), position = "identity") 

ggplot(data = diamonds) +
    geom_bar(mapping = aes(x = cut, fill = clarity), position = "fill") 

ggplot(data = diamonds) +
    geom_bar(mapping = aes(x = cut, fill = clarity), position = "dodge") 

# jitter aggiunge un pochino di rumore per ogni punto in modo che non si sovrappongano
ggplot(data = mpg) +
    geom_point(mapping = aes(x = displ, y = hwy),
               position = "jitter")

Infine una breve introduzione al sistema di coordinate

il sistema di default è cartesiano.
coord_flip() cambia l’orientamento degli assi
ggplot(data = mpg, aes(x = class, y = hwy, fill = class)) +
    geom_boxplot()

ggplot(data = mpg, aes(x = class, y = hwy, fill = class)) +
    geom_boxplot() +
    coord_flip()

# coord_polar utilizza le coordinate polari

bar <- ggplot(data = diamonds) +
    geom_bar(mapping = aes(x = cut, fill = cut),
             show.legend = FALSE,
             width = 1) +
    theme(aspect.ratio = 1) +
    labs(x = NULL, y = NULL)

bar + coord_flip()

bar + coord_polar()

ggplot(data = mpg) +
    geom_bar(mapping = aes(x = drv, fill = drv), 
             position = "stack") +
    coord_polar()