Adding p-value brackets to ggplot with two grouping variables for stats and a faceting variable?

114 Views Asked by At

I have a large data set with several variables I want to take into account when graphing. Two are grouping variables, and one is the variable used for statistics. One of the grouping variables will be the fill in the plot, and the other will be the facet. I can graph this okay and get the significance on the graph, but no matter what I try there is no bracket line. Is there a way to fix this?

Here is some sample code using a manipulated version of mtcars to replicate my issue:

datamt <- mtcars |>
  group_by(cyl, am) |>
  tidyr::unite("group", cyl, am,  sep=" ", remove = F) |>
  filter(cyl!="8")

datamt$compare <- rep(c("A", "B"),len=18)

datamt <- rbind(datamt, datamt)

stat.test <- datamt |>
  group_by(group)|> 
  t_test(formula=mpg~compare, paired=F)
  add_significance() |>
  add_xy_position(fun="max", formula=mpg~compare, x = "group", 
                  dodge = 0.8, step.increase = 0)
datamt <- merge(datamt, stat.test, by.x="group", by.y="group")



ggplot(data=datamt, aes(x=group, y=mpg, fill=compare)) +
         stat_boxplot(inherit.aes=T, geom ='errorbar', width = 0.6, lwd=1, 
                      position=position_dodge(0.8), color="black")+
         geom_boxplot() +
         facet_wrap(facets=vars(cyl), ncol=4, scales="free")+
         stat_pvalue_manual(data=datamt, 
                            label="p.signif", hide.ns = T, x="group",
                            y.position = (datamt|>
                                            filter(p.signif!="ns"))$y.position*1.1)
   
0

There are 0 best solutions below