2

I am trying to plot a bar graph using ggplot. The graph is displaying as I would like but I can't figure out how to add an Asterix "*" above some of the bars to show significance. Whenever I try it wither adds them to all of the bars or completely seems to skew the graph.

I need to have an Asterix only above Group A: Treatment A and Treatment B; Group B: Treatment A

Thankyou!!

Treatment <- rep(c("Treatment A","Treatment A","Treatment B","Treatment B"), 3)
Group <- c(rep(c("A. Paired cohort"), 4),rep(c("B. Low cohort"), 4),rep(c("C. Normal cohort"), 4))
Outcome <- rep(c("Outcome P","Outcome D"),6)
Percent <- c(6.7,3.3,22.6,16.1,4.9,2.4,25,15,8.2,4.1,20.8,17)
df <- data.frame(Treatment,Group,Outcome,Percent)

#keep original order, not alphabetised
df$Outcome <- factor(df$Outcome, levels = unique(df$Outcome)

#plot graph  
ggplot(df, 
                       aes(x=Outcome, y=Percent)) +
   geom_bar(aes(fill=Treatment),stat="identity", position="dodge")+
   theme_classic() +
    scale_fill_grey() +
    xlab("") + ylab("%") +
   facet_wrap(~Group) +
   ylim(0,40) 
Soph P
  • 33
  • 1
  • 4

1 Answers1

1

One option would be to

  1. Add an indicator variable to your data to indicate signifcance using e.g. dplyr::case_when.
  2. This indicator could then be used in geom_text to conditionally add an asterisk as a label on top of the desired bars. To align the * with bars we have to map Treatment on the group aes and make use of position_dodge(width = .9), where .9 is the default width of a geom_bar/col. Additionally I set vjust=-.1 to put the labels slightly above the bars.
library(ggplot2)
library(dplyr)

df$significant <- dplyr::case_when(
  grepl("^A", df$Group) & grepl("(A|B)$", df$Treatment) ~ TRUE,
  grepl("^B", df$Group) & grepl("A$", df$Treatment) ~ TRUE,
  TRUE ~ FALSE
)

# plot graph
ggplot(df, aes(x = Outcome, y = Percent)) +
  geom_col(aes(fill = Treatment), position = "dodge") +
  geom_text(aes(label = ifelse(significant, "*", ""), group = Treatment), 
            position = position_dodge(width = .9), vjust = -.1, size = 20 / .pt) +
  theme_classic() +
  scale_fill_grey() +
  labs(x = "", y = "%") +
  facet_wrap(~Group) +
  ylim(0, 40)

stefan
  • 90,330
  • 6
  • 25
  • 51