Another grouping variable can easily be added to a plot. This variable should be a factor; if not, the variable will be coerced into a factor, which can sometimes lead to issues.
str(pss$gndr)
## Factor w/ 2 levels "female","male": 2 2 2 1 1 1 2 1 1 2 ...
barGroup <- ggplot(
pss,
aes(
edu,
fill = gndr
)
) +
geom_bar()
barGroup
We can also position the sub-bars next to each other instead of stacking them:
barGroup <- ggplot(
pss,
aes(
edu,
fill = gndr
)
) +
geom_bar(position = position_dodge())
barGroup
Just like before, we can adjust all other options as well:
barGroup +
scale_y_continuous(
breaks = seq(
0,
800,
100
),
limits = c(
0,
800
)
) +
geom_text(
stat = "count",
aes(label= ..count..),
vjust = -1,
size = 3.5,
position = position_dodge(0.9)
) +
labs(
x = "Bildungslevel",
y = "Häufigkeiten",
title = "My first fancy ggplot"
) +
scale_fill_manual(
name = "Gender",
labels = c(
"Female",
"Male"
),
values = beyonce_palette(72)
)
That’s how simple it is! Let’s move on to the other types of plots!