How to Create Stacked Bar Plots with Error Bars and P-values



How to Create Stacked Bar Plots with Error Bars and P-values

# 1. Load required R packages
suppressPackageStartupMessages(library(ggpubr))
suppressPackageStartupMessages(library(rstatix))

# 2. Data preparation
df <- ToothGrowth
df$dose <- factor(df$dose)

# 3. Statistical tests
res.stats <- df %>%
  group_by(dose) %>%
  t_test(len ~ supp) %>%
  adjust_pvalue() %>%
  add_significance()
res.stats
## # A tibble: 3 x 11
##   dose  .y.   group1 group2    n1    n2 statistic    df       p   p.adj p.adj.signif
##   <fct> <chr> <chr>  <chr>  <int> <int>     <dbl> <dbl>   <dbl>   <dbl> <chr>       
## 1 0.5   len   OJ     VC        10    10    3.17    15.0 0.00636 0.0127  *           
## 2 1     len   OJ     VC        10    10    4.03    15.4 0.00104 0.00312 **          
## 3 2     len   OJ     VC        10    10   -0.0461  14.0 0.964   0.964   ns
# 4. Create a stacked bar plot, add "mean_se" error bars
p <- ggbarplot(
  df, x = "dose", y = "len", add = "mean_se",
   color = "supp", palette = "jco"
  )

# 5. Add p-values to the bar plot using ggpubr verbs
p + stat_pvalue_manual(
  res.stats, x = "dose", y.position = c(30, 45, 60),
  label = "p.adj.signif"
)

plot of chunk stacked-barplot-with-error-bars-and-p-values

# or use ggplot2 verbs
p + geom_text(
  aes(x = dose, y = c(25, 42, 60), label = p.adj.signif),
  data = res.stats
)

plot of chunk stacked-barplot-with-error-bars-and-p-values



Version: Français





Comment ( 1 )

  • Steph

    What if you had an additional level? Like you have dose but then you also have a group within dose? So, you have the doses repeated for Group A, Group B, and Group C, and you want the stacked bars for the dose as you have here but want that repeated for Group A, Group B, and Group C, and have them side by side so you would have 9 stacked bar plots with the error bars instead of 3. Thank you!

Give a comment

Want to post an issue with R? If yes, please make sure you have read this: How to Include Reproducible R Script Examples in Datanovia Comments