Was ist ggplot2?
Warum ggplot2?
Grafiken sehen professionell aus.
Sehr flexibel und gut erweiterbar.
Ideal für Datenanalyse-Projekte.
ggplot(data = DATEN, aes(x = X, y = Y)) +
geom_POINT() +
labs(title="Titel", x="X-Achse", y="Y-Achse") +
theme_minimal()
ggplot(data = DATEN, aes(x = X, y = Y)) : welche Daten und welche Variablen?
geom_…() : Welche Art von Grafik (Punkte, Linien, Balken …)?
labs() : Achsenbeschriftungen und Titel.
theme_…() : Gestaltung der Grafik.
geom_point() : - Streudiagramm Punkteplot von x vs y
geom_line() : Liniendiagramm Linie durch Datenpunkte
geom_bar() : Balkendiagramm Häufigkeiten anzeigen
geom_histogram() : Histogramm Verteilung einer Variablen
geom_boxplot() : Boxplot Quartile & Ausreisser
ggplot(mtcars, aes(x=wt, y=mpg, color=factor(cyl))) +
geom_point(size=3)
Facetten: kleine Multiples für verschiedene Gruppen.
ggplot(mtcars, aes(x=wt, y=mpg)) +
geom_point() +
facet_wrap(~cyl) # Diagramme pro Zylinderanzahl
# Beispiel-Daten
daten <- data.frame(
x = 1:5,
y = c(3, 5, 2, 8, 7)
)
# ggplot verwenden
library(ggplot2)
ggplot(daten, aes(x = x, y = y)) +
geom_point()
ggplot(daten, aes(x = x, y = y, color = y, size = y)) +
geom_point() +
labs(title = "Scatterplot mit Farbe und Grösse") +
theme_classic()
ggplot(daten, aes(x = x, y = y)) +
geom_line(color = "blue", size = 1.2) +
geom_point() +
labs(title = "Liniendiagramm") +
theme_light()
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
ggplot(daten, aes(x = y)) +
geom_histogram(binwidth = 1, fill = "skyblue", color = "black") +
labs(title = "Histogramm der y-Werte") +
theme_minimal()
# Beispiel mit Gruppen
daten2 <- data.frame(
Gruppe = rep(c("A", "B", "C"), each = 5),
Wert = c(3,4,2,5,6, 5,7,6,8,7, 4,5,6,3,4)
)
ggplot(daten2, aes(x = Gruppe, y = Wert, fill = Gruppe)) +
geom_boxplot() +
labs(title = "Boxplot nach Gruppen") +
theme_minimal()
ggplot(daten2, aes(x = Wert)) +
geom_histogram(binwidth = 1, fill = "orange", color = "black") +
facet_wrap(~Gruppe) +
labs(title = "Histogramme pro Gruppe") +
theme_light()
geom_point() → Punkteplot
geom_line() → Linienplot
geom_histogram() → Histogramm
geom_boxplot() → Boxplot
facet_wrap(~Gruppe) → Plots für jede Gruppe
aes() → Mapping von Variablen auf Achsen, Farbe, Grösse
theme_…() → Optik der Grafik