rggplot2colorsggpubrjitter

Coloring mean +/- sd jitter points on a ggbarplot?


I have a dataframe like this:

   my.var group1 group2
c1    3.8      c    gp1
c2    3.9      c    gp2
c3    4.3      c    gp3
c4    3.7      c    gp4
s1    3.6      s    gp1
s2    3.9      s    gp2
s3    3.2      s    gp3
s4    3.6      s    gp4
x1    3.6      x    gp1
x2    4.4      x    gp2
x3    3.9      x    gp3
x4    4.4      x    gp4

The dataframe dput object:

df <- structure(list(my.var = c(3.8, 3.9, 4.3, 3.7, 3.6, 3.9, 3.2, 
3.6, 3.6, 4.4, 3.9, 4.4), group1 = c("c", "c", "c", "c", "s", 
"s", "s", "s", "x", "x", "x", "x"), group2 = c("gp1", "gp2", 
"gp3", "gp4", "gp1", "gp2", "gp3", "gp4", "gp1", "gp2", "gp3", 
"gp4")), row.names = c("c1", "c2", "c3", "c4", "s1", "s2", "s3", 
"s4", "x1", "x2", "x3", "x4"), class = "data.frame")

I have created a barplot using ggpubr showing the mean +/- sd for my.var for group1, but I would also like the jitter points to be coloured by group2. How can I colour the mean jitter points by group 2?

My code so far:

library(ggpubr)

ggbarplot(df, x="group1", y="my.var", 
          add=c("mean_sd", "jitter")) +
  stat_compare_means(comparisons=list(c("s", "c"), c("x", "c")), method="t.test", 
                     label = "p.signif")

Solution

  • You could use geom_jitter from ggplot2 and assign the group2 variable as color aesthetic like this:

    library(ggpubr)
    ggbarplot(df, x="group1", y="my.var", 
              add=c("mean_sd")) +
      geom_jitter(aes(color = group2)) +
      stat_compare_means(comparisons=list(c("s", "c"), c("x", "c")), method="t.test", 
                         label = "p.signif")
    

    Created on 2023-03-12 with reprex v2.0.2