2

I want to do a boxplot in ggpubr, with an added jitter. Unfortunately, it jitters on the y-axis, which really is confusing for the viewer.

Setup:

library(ggpubr)

df <- tibble(
  group = rep(c("Group1", "Group2", "Group3"), each = 10),
  value = sample(0:3, 30, replace = TRUE) # 300 samples with replacement
)

Code for two graphs:

ggboxplot(df, x = "group", y = "value", add = "jitter", color = "group", palette = "jco") +
  rremove("x.text") +
  rremove("xlab") +
  rotate_x_text(angle = 45)

ggboxplot(df, x = "group", y = "value", add = "dotplot", color = "group", palette = "jco") +
  rremove("x.text") +
  rremove("xlab") +
  rotate_x_text(angle = 45)

The jitter graph (with jitter on both x and y axes)

enter image description here

The dotplot graph (with the position reflecting the real Y-axis values)

enter image description here

How do I get ggpubr to only jitter on the x-axis, not on the y-axis?

flashton
  • 208
  • 1
  • 2
  • 8

3 Answers3

1

You could also add the jitter to the add.params argument of ggboxplot to add the position_jitter only horizontally like this:

library(ggpubr)

ggboxplot(df, x = "group", y = "value", add = "dotplot", color = "group", palette = "jco",
          add.params = list(position = position_jitter(w = 0.2, h = 0))) +
  rremove("x.text") +
  rremove("xlab") +
  rotate_x_text(angle = 45)

Created on 2023-09-01 with reprex v2.0.2

Quinten
  • 35,235
  • 5
  • 20
  • 53
0

Ah, you can just add a ggplot2 geom_jitter

ggboxplot(df, x = "group", y = "value", color = "group", palette = "jco") +
  rremove("x.text") +
  rremove("xlab") +
  rotate_x_text(angle = 45) +
  geom_jitter(aes(color = group), width = 0.2, height = 0)

enter image description here

flashton
  • 208
  • 1
  • 2
  • 8
0

I was able to do it with ggplot2 if you are willing to change:

ggplot(df, aes(x = group, y = value, color = group)) +
  geom_boxplot() +
  geom_point(position = position_jitter(width = 0)) +
  theme_classic() +
  theme(axis.text.x = element_text(angle = 45, vjust = 0.5, hjust=1),
        legend.position = "top",
        text = element_text(size=18)) +
  xlab("") 

enter image description here

Matt B
  • 306
  • 6
  • Thanks for the answer, but I was looking for a ggpubr solution specifically. I'm using the facet feature, but I didn't include that in the example to keep things clear. – flashton Sep 01 '23 at 09:30