Boxplots kennst du aus der Statistik-Vorlesung. In Boxplots sind die Quartile angegeben sowie das Minimum und Maximum (oder Ausreißer). Jetzt lernst du die einzelnen Funktionen genauer kennen, wie du ein Boxplot darstellen kannst. Wir stellen zwei Funktionen vor: geom_boxplot()
oder ggboxplot()
. Wir nutzen Boxplots für die Darstellung einer metrischen Variablen. Boxplots einer metrischen Variable können auch nach einer Gruppenvariable aufgeteilt werden.
Zusätzlich stellen wir auf der letzten Seite noch rainclouds vor. Diese sind ähnlich einem Boxplot, erhalten aber noch zusätliche Informationen darüber wie die Werte verteilt sind.
geom_boxplot()
Die Boxplots des Alters können wir ganz einfach erstellen. Hierzu nutzen wir die Funktion geom_boxplot()
:
boxplot <- ggplot(
pss,
aes(agea)
) +
geom_boxplot()
boxplot
## Warning: Removed 157 rows containing non-finite outside the scale range
## (`stat_boxplot()`).
Auf der x-Achse ist nun die metrische Variable Alter angegeben. Die Darstellung der y-Achse ist hier etwas verwirrend, da diese inhaltlich nicht interpretiert wird.
ggplot
benötigt diese aber zur Darstellung. Daher kann man diese einfach anpassen und das Boxplot drehen:
boxplot <- ggplot(
pss,
aes(agea)
) +
geom_boxplot() +
coord_flip() +
scale_y_continuous(breaks = NULL)
boxplot
## Warning: Removed 157 rows containing non-finite outside the scale range
## (`stat_boxplot()`).
Im Folgenden werden wir das Boxplot von Alter in Abhängigkeit vom Distrikt ausgeben lassen. Oftmals will man die Verteilung einer metrischen Variable auf einer kategoriellen Variable ausgeben lassen. Dazu fügst du innerhalb der ggplot()
Funktion im Argument aes
einfach die Gruppenvariable hinzu. Denk dran: Wir haben die Achsen getauscht, also ist die Gruppenvariable auf der x-Achse (1. Argument in aes
), auch wenn es im Plot auf der y-Achse auftaucht!
boxplotDistrict <- ggplot(
pss,
aes(
district,
agea,
fill = district
)
) +
geom_boxplot()
boxplotDistrict
## Warning: Removed 157 rows containing non-finite outside the scale range
## (`stat_boxplot()`).
Wie zuvor können wir den Plot leicht anpassen:
boxplotDistrict +
scale_fill_manual(
name = "Distrikt",
values = cbp1
) +
scale_x_discrete(
limits = c(
"Distrikt 10",
"Distrikt 7",
"Distrikt 12",
"Distrikt 5",
"Distrikt 1"
)
) +
scale_y_continuous(
breaks = seq(
0,
100,
5
)
) +
labs(
x = "District",
y = "Age in years",
title = "Boxplots of Age by District"
) +
coord_flip()
## Warning: Removed 157 rows containing non-finite outside the scale range
## (`stat_boxplot()`).
Auf der nächsten Seite lernst du eine Alternative kennen!