Home > database >  How do I manually add brackets to a boxplot with a categorical x axis varibale?
How do I manually add brackets to a boxplot with a categorical x axis varibale?

Time:10-20

I have a dataset with counts of two different fish species at different depths and made a graph with the following code:

depth<-c(5,5,5,5,5,5,5,5,5,5,5,5,5,5,10,10,10,10,10,10,10,10,10,10,10,10,10,10)
count<-c(10,6,13,2,16,4,9,1,17,3,20,4,11,5,13,14,12,10,15,7,14,8,16,5,12,9,15,10)
species<- c('a','b','a','b','a','b','a','b','a','b','a','b','a','b','a','b','a','b','a','b','a','b','a','b','a','b','a','b')
df<-data.frame(depth, count, species)
df

df$depth<- factor(df$depth, levels = c("5", "10"))

#making the plot
ggplot(data=df, aes(depth, count, fill=species)) geom_boxplot() 
   labs(x="Depth", y="Number", fill= "Species")


easy plot

I now want to manually add brackets that indicate the significant differences between the two fish species per depth. I managed to add brackets but I can only make them go from depth=5 to depth=10 and i cannot find a way to point from one species at depth=5 to the other. This is how I add brackets between the two depths (what I don't want to do):

   labs(x="Depth", y="Number", fill= "Species") geom_bracket(
    xmin = c("5","5"), xmax = c("10","10"),
    y.position = c(40,30) ,label.size = 5, label = c("***", "*"),inherit.aes = FALSE,
    tip.length = c(0.01, 0.01))

Which numbers do I have to use for xmin and xmax to draw a bracket between the two species at the same depth?

Thank you in advance, Anni

CodePudding user response:

You could use ggplot_build to check the x positions of your boxplot and use them as xmin and xmax like this:

library(ggplot2)
library(ggpubr)
#making the plot
p <- ggplot(data=df, aes(depth, count, fill=species)) 
  geom_boxplot() 
  labs(x="Depth", y="Number", fill= "Species") 

q <- ggplot_build(p)
q$data[[1]]$x[1:2]
#> [1] 0.8125 1.1875
#> attr(,"class")
#> [1] "mapped_discrete" "numeric"
q$data[[1]]$x[3:4]
#> [1] 1.8125 2.1875
#> attr(,"class")
#> [1] "mapped_discrete" "numeric"

p   geom_bracket(
    xmin = c(q$data[[1]]$x[1:2]), xmax = c(q$data[[1]]$x[3:4]),
    y.position = c(40,30) ,label.size = 5, label = c("***", "*"),inherit.aes = FALSE,
    tip.length = c(0.01, 0.01))

Created on 2022-10-19 with reprex v2.0.2

  • Related