Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Jittered points do not align with position of boxplot for nested categorial variables

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()

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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())

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading