When I try to add p-values to multifacet ggplot with different scales, they are getting shifted, although in facet_wrap to ggplot and add_xy_position to stats I indicate scales="free":
my code chunks:
stat_c <- dat_c %>%
group_by(antigen , region) %>%
wilcox_test(norm_mean ~ genotype , alternative = "greater") %>%
adjust_pvalue(method = "bonferroni") %>%
add_significance("p.adj") %>%
add_xy_position(x = "region" , dodge = 0.8 , scales = "free")
plt_c <- ggplot(dat_c , aes(x = region , y = norm_mean , color = genotype)) +
geom_boxplot(outlier.shape=NA) +
geom_jitter(position=position_jitterdodge()) +
facet_wrap(~antigen , scales = "free" ) +
ggtitle(label = "DRS hit IHC in tent5c KO")
plt_c +
stat_pvalue_manual(stat_c , label = "p.adj") +
scale_y_continuous(expand = expansion(mult = c(0,0.1)))
I'd be supergrateful for any help!
I just ran into the same issue with some data I was working with. The trick is to calculate the pvalues for each facet independently and rbind the tables togehter. This way the x-values for each facet are derived independently. Your solution may look something like this:
antigens = levels(factor(dat_c$antigen))
i = 0
res.stat.test = ""
for (a in antigens){
print(a)
df = dat_c %>% filter(antigen == a)
stat.test = df %>%
group_by(region) %>%
wilcox_test(., norm_mean ~ genotype, alternative = "greater") %>%
adjust_pvalue(method = "bonferroni") %>%
add_significance("p.adj") %>%
add_xy_position(x = "region", fun = "max", dodge = 0.8)
if (i == 0){
res.stat.test = stat.test
} else {
res.stat.test = rbind(res.stat.test, stat.test)
}
}
plt_c <- ggplot(dat_c , aes(x = region , y = norm_mean , color = genotype)) +
geom_boxplot(outlier.shape=NA) +
geom_jitter(position=position_jitterdodge()) +
facet_wrap(~antigen , scales = "free" ) +
stat_pvalue_manual(res.stat.test, label = "p.adj", tip.length = 0.05, step.increase = 0.01) +
ggtitle(label = "DRS hit IHC in tent5c KO")