Search code examples
rggplot2boxplotggpubr

How to insert Cohen's d in the boxplots in R


Data are as follows:

   d <- data.frame(
        Class= rep(c('First', 'Second'), 10),
        Response= rnorm(20,14,4)
    )

Here is my codes to get the boxplots and Cohen's d:

library(ggpubr)
library(ggplot2)
library(effsize)
p <- ggboxplot(d, x = "Class", y = "Response",
               color = "Class", palette = "jco",
               add = "jitter")
p + stat_compare_means(method = "t.test")
with(d, cohen.d(Response,Class))

I want to use only my codes to add Cohen's d to the boxplot.

Here is the intended outcome

enter image description here


Solution

  • If you want to do it all within the ggpubr framework, you can try:

    library(ggpubr)
    library(ggplot2)
    library(effsize)
    
    ggboxplot(d, x = "Class", y = "Response", color = "Class", palette = "jco",
             add = "jitter") +
      stat_compare_means(method = "t.test", 
            aes(label = paste0("t-test p = ",after_stat(p.adj),
                  "; Cohen's D = ",
                  with(d, round(cohen.d(Response,Class)$estimate, 3))))) 
    

    Created on 2023-02-07 with reprex v2.0.2