Search code examples
rggplot2tidyversep-valueggpubr

P values missing in faceted ggviolin plot (R, ggplot2)


I have this code:

 library(ggplot2)
 library(ggpubr)
 df <- ToothGrowth
 df$dose <- as.factor(df$dose)
 df$group <- c(rep(c("grp1", "grp2"), 5), rep(c("grp1", "grp2", "grp3"), 6), 
           rep(c("grp1", "grp2"), 6), rep(c("grp1", "grp2", "grp3"), 6), "grp2", "grp3")
 plot <- ggviolin(df, x = "group", y = "len", fill = "group",
                  width = 0.8, alpha = 0.5, draw_quantiles = c(0.25, 0.5, 0.75), facet.by = 'dose') +
          scale_fill_manual(values = c("#00AFBB", "#E7B800", "#FC4E07")) + 
          stat_compare_means(comparisons = list(c("grp1","grp2"),c("grp2","grp3")), 
                  label = "p.format")

In the first facet, the p value comparing grp1 and grp2 is missing, although it can be calculated. I think this is because grp3 has no data, but how can I get it to show up? Importantly, my real data have many more facets, so I would like a solution that works across facets rather than making adjustments to specific facets, which I have found solutions for. Thank you.


Solution

  • Not sure if this answers your question. It shows the missing comparisons.

    plot <- ggviolin(df,
      x = "group", y = "len", fill = "group",
      width = 0.8, alpha = 0.5, draw_quantiles = c(0.25, 0.5, 0.75), facet.by = "dose"
    ) +
      scale_fill_manual(values = c("#00AFBB", "#E7B800", "#FC4E07")) +
      stat_compare_means(
        comparisons = list(c("grp1", "grp2"), c("grp2", "grp3")),
        label = "p.format"
      ) +
      stat_compare_means(
        comparisons = list(c("grp1", "grp2")),
        label = "p.format"
      )
    
    

    enter image description here