R ggplot2 - perform pairwise tests per pair in a facet and show the p-values with ggsignif

微笑、不失礼 提交于 2019-11-29 12:34:07

I used the idea from here. In brief, plot the plot, get the underlying data, update the annotations and plot the final picture with facets.

# first save the plot in variable
myplot <- ggplot(alpha.sub, aes(x=DB, y=Value)) + 
  geom_boxplot(aes(fill=Group)) +
  facet_grid(~Group) +
  geom_signif(test="wilcox.test", comparisons = list(c("DATABASE1", "DATABASE2")), map_signif_level = F)
# a plot with all significance layer per facet group. 
myplot

# build the plot, e.g. get a list of data frames
myplot2 <- ggplot_build(myplot)
# in list 2 you have access to each annotation 
head(myplot2$data[[2]])
  x xend        y     yend annotation                 group PANEL shape colour textsize angle hjust vjust alpha family
1 1    1 3.968526 4.063608       0.11 DATABASE1-DATABASE2-1     1    19  black     3.88     0   0.5     0    NA       
2 1    2 4.063608 4.063608       0.11 DATABASE1-DATABASE2-1     1    19  black     3.88     0   0.5     0    NA       
3 2    2 4.063608 3.968526       0.11 DATABASE1-DATABASE2-1     1    19  black     3.88     0   0.5     0    NA       
4 1    1 3.968526 4.063608      0.035 DATABASE1-DATABASE2-1     2    19  black     3.88     0   0.5     0    NA       
5 1    2 4.063608 4.063608      0.035 DATABASE1-DATABASE2-1     2    19  black     3.88     0   0.5     0    NA       
6 2    2 4.063608 3.968526      0.035 DATABASE1-DATABASE2-1     2    19  black     3.88     0   0.5     0    NA       
  fontface lineheight linetype size
1        1        1.2        1  0.5
2        1        1.2        1  0.5
3        1        1.2        1  0.5
4        1        1.2        1  0.5
5        1        1.2        1  0.5
6        1        1.2        1  0.5

# now you can remove or update the annotation
# get all ADJUSTED PVALUES
pv <- tidy(with(alpha.sub, pairwise.wilcox.test(Value, interaction(Group,DB), p.adjust.method = "BH")))
# create final dataset using dplyr
pv_final <- pv %>% 
  separate(group1, c("g1_1", "g1_2")) %>% 
  separate(group2, c("g2_1", "g2_2")) %>% 
  filter(g1_1 == g2_1) %>% 
  mutate(p=ifelse(p.value > 0.05, "", ifelse(p.value > 0.01,"*", "**")))

# each pvalue is repeated three times in this dataset.  
myplot2$data[[2]]$annotation <- rep(pv_final$p, each=3)
# remove non significants
myplot2$data[[2]] <- myplot2$data[[2]][myplot2$data[[2]]$annotation != "",]
# and the final plot
plot(ggplot_gtable(myplot2))

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!