csdaw / ggprism

ggplot2 extension inspired by GraphPad Prism
https://csdaw.github.io/ggprism/
170 stars 21 forks source link

Can't seem to adjust x-position for brackets in interaction plots with add_pvalue #21

Closed Oriane4972 closed 2 years ago

Oriane4972 commented 2 years ago

Hello,

I'm new to plotting p-values on interaction plots, and I've been working off the piece of code below (source).

I've been trying to adjust the x-position of the brackets, such that for each pairwise comparison, the left end of the bracket is aligned with the middle of the first boxplot being considered, and the right end of the bracket is aligned with the middle of the second boxplot being considered.

In other words, I would like xmin in df_p_val to reflect the dose & supp combination of the first group in the pairwise comparison -- not just its dose.

Thank you very much in advance for any guidance you may be able to provide!

df_p_val <- ToothGrowth %>% 
  rstatix::group_by(supp) %>% 
  rstatix::t_test(len ~ dose) %>% 
  rstatix::add_xy_position()

p <- ggplot(ToothGrowth, aes(x = factor(dose), y = len)) + 
  geom_boxplot(aes(fill = supp)) + 
  theme_prism()

# remember colour and step.group.by are referring to a column name in df_p_val
p + add_pvalue(df_p_val, 
               label = "p = {p.adj}",
               colour = "supp",
               fontface = "bold",
               step.group.by = "supp",
               step.increase = 0.1,
               tip.length = 0,
               bracket.colour = "black",
               show.legend = FALSE)
csdaw commented 2 years ago

Hi there,

The easiest way to do this is manually (although there should be a way using rstatix::add_xy_position() directly but I can't immediately figure out how).

library(ggplot2)
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(ggprism)

# manually dodge xmin and xmax of bracket lines
df_p_val <- ToothGrowth %>% 
  rstatix::group_by(supp) %>% 
  rstatix::t_test(len ~ dose) %>% 
  rstatix::add_xy_position() %>% 
  mutate(xmin = xmin + rep(c(-0.2, 0.2), each = 3),
         xmax = xmax + rep(c(-0.2, 0.2), each = 3))

p <- ggplot(ToothGrowth, aes(x = factor(dose), y = len)) + 
  geom_boxplot(aes(fill = supp)) + 
  theme_prism()

# need to specify xmin and xmax columns here
p + add_pvalue(df_p_val, 
               xmin = 'xmin',
               xmax = 'xmax',
               label = "p = {p.adj}",
               colour = "supp",
               fontface = "bold",
               step.group.by = "supp",
               step.increase = 0.1,
               tip.length = 0,
               bracket.colour = "black",
               show.legend = FALSE)

Created on 2022-11-02 with reprex v2.0.2