I have data with two categorical variables. I want to plot boxplots together with jittered points where on categorical variable is depicted on the x-axis, the other on as colour. However, I do not manage to align the position of the jittered points with the respective boxplots. Any ideas?
That’s my code:
library(ggplot2)
# Data
set.seed(8)
y <- rnorm(200)
group <- sample(LETTERS[1:3], size = 200,
replace = TRUE)
group2 <- sample(letters[4:5], size = 200,
replace = TRUE)
df <- data.frame(y, group, group2)
# Box plot by group and group2 with jitter
ggplot(df, aes(x = group, y = y, colour = group2)) +
geom_boxplot(outlier.shape = NA) +
geom_jitter()
>Solution :
You have to dodge your jittered points to align them with the boxplots using position = position_jitterdodge():
library(ggplot2)
# Box plot by group and group2 with jitter
ggplot(df, aes(x = group, y = y, colour = group2)) +
geom_boxplot(outlier.shape = NA) +
geom_jitter(position = position_jitterdodge())

