'How create horizontal brackets for variation between columns in ggplot2 above barchart?

"variation between weeks"

The dataset is here: week,session week1,100 week2,120 week3,90 week4,180

And Graph code without brackets is here:

  ggplot(data=df, aes(x=week, y=session)) +
  geom_bar(stat="identity", fill="steelblue")+
  geom_text(aes(label=session), vjust=1.6, color="white", size=3.5)+
  theme_minimal()


Solution 1:[1]

There is the function ggpubr::stat_pvalue_manual originally designed for significance bars testing two groups of data points:

library(ggpubr)
#> Loading required package: ggplot2
library(tidyverse)

data <- tribble(
  ~group, ~value,
  1, 100,
  2, 120,
  3, 90,
  4, 180,
)

bar_data <- tribble(
  ~group1, ~group2, ~label, ~y.position,
  1,2, "20%", 200,
  2,3, "-25%", 200,
  3,4, "200%", 200
)

data %>%
  ggplot(aes(group, value)) +
    geom_col() +
    stat_pvalue_manual(bar_data, bracket.shorten = 0.1)

Created on 2022-04-27 by the reprex package (v2.0.0)

Differences can also be automatically created e.g. using

bar_data <- 
  data %>%
  transmute(
    group1 = group,
    group2 = group + 1,
    diff = (lead(value) - value) / value,
    label = paste0(diff * 100, "%"),
    y.position = 200
   ) %>%
   filter(!is.na(diff))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1