Search code examples
rggplot2geom-barsignificance

Significant annotations merge instead of showing individually in R


The significant annotations merge when they are the same and are plotted on top of each other, instead of plotting individually. How could I fix this?

data <- tibble::tibble(
  value = c(1.63, 1.39,1.22,1.14,1.98,-1.34,-1.34,-1.29,-1.11,-1.23),
  variable = c("A", "B","C","D", "E", "F", "G", "H", "I" , "J"),
  type = c(rep("p",5),rep("n",5)))

ggplot(data, aes(x=variable, y=value) )+
  geom_bar(stat="identity", width = 0.8)+
  theme_classic() + scale_fill_grey()+
   geom_signif(stat="identity",
              data=data.frame(x=c(0.875, 1.875, 2.875, 3.875, 4.875, 5.875, 6.875, 7.875, 8.875, 9.875), xend=c(1.125, 2.125, 3.125, 4.125, 5.125, 6.125,7.125,8.125,9.125, 10.125),
                               y=c(0.1, 0.1, 0.1, 0.1, 0.1, -0.1, -0.1,-0.1,-0.1,-0.1), annotation=c("NS", "*", "***", "***","***",  "**", "*", "*", ".", "***")),
              aes(x=x,xend=xend, y=y, yend=y, annotation=annotation))

enter image description here


Solution

  • It seems to work well if you change your x values to match the factor levels:

    ggplot(data, aes(x = variable, y = value)) +
      geom_bar(stat = "identity", width = 0.8) +
      theme_classic() + 
      scale_fill_grey() +
       geom_signif(stat = "identity",
                  data = data.frame(x = LETTERS[1:10], 
                                    xend = 1:10 + 0.125,
                                    y = rep(0.1, -0.1, each = 5), 
                                    annotation = c("NS", "*", "***", "***","***",  "**", "*", "*", ".", "***")),
                  aes(x = x, xend = xend, y = y, yend = y, annotation = annotation))
    
                  aes(x=x,xend=xend, y=y, yend=y, annotation=annotation))
    

    enter image description here