How do I annotate p-values onto a faceted bar plot

2019-06-09 12:05发布

问题:

I'd like to know if it's possible to annotate p-values at the top of the graph and in between 2 bar plots. In my case, using ggplot2, I have a faceted graph with 2 conditions (Passage and Isolated) and in each condition, there are 3 levels/3 bar graphs (GA, CH, KO). If it's possible, I have some p-values from pairwise comparisons (GA vs CH, CH vs KO, GA vs KO) that I would like to show on the graph itself.

My ggplot script is below:

#plot
dev.new()
accentrating_comb <- ggplot(ch_ko_am_comb, aes(x=speaker_type, y=Mean, fill=speaker_type)) + 
    geom_bar(position=position_dodge(width=1), stat="identity", colour="black", size=.5) + 
    geom_errorbar(aes(ymin=cllo, ymax=clup), colour="black", size=.3, width=.2, position=position_dodge(width=1)) +
    geom_text(aes(label=lable), colour="black", vjust=-0.5, size=10, hjust=-2) +
    coord_cartesian(ylim=c(0,10)) +
    ylab("Mean Accent Rating") +
    scale_fill_brewer(type = "div", palette = "Greys") +
    guides(fill=guide_legend("Accent")) +
    theme_bw() +
    theme(plot.title = element_text(size = 22), axis.title.x = element_blank(), axis.title.y = element_text(size = 14), axis.line = element_line(colour = "black"), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), strip.text.x = element_text(size = 14), axis.text.x = element_text(size=14), legend.title=element_text(size=14), legend.text=element_text(size=14), panel.margin.x=unit(20,"pt")) +
    facet_wrap( ~ condition )  #this creates multiple panels 
print(accentrating_comb)
#dev.off()

回答1:

In order to produce a plot similar to yours (two facets, 3 variables in each), I have created a dummy data set using the iris and ToothGrowth data sets.

This solution uses the ggsignif package to annotate the plot facets with p values, as well as showing how to add the prefix p= to the annotations, if desired.

library(ggplot2)
library(ggsignif)

data("ToothGrowth")
data('iris')

iris2<-iris[c(1:10,50:60,100:110,61:70,11:20,111:118),]

big_data<-cbind(iris2,ToothGrowth) #dummy data


plot<-ggplot(big_data, aes(Species, len)) +
  geom_boxplot() +
  geom_signif(comparisons =list(c("setosa", "virginica"),c('setosa','versicolor'),c('virginica','versicolor')),
              step_increase = 0.1)+
  facet_wrap(~supp) #create initial plot

pg<-ggplot_build(plot) #disassemble plot and obtain information

pv<-pg$data[[2]]$annotation #seek out p values

new<-as.factor(paste('p=',pv)) #add the desired prefix

pg$data[[2]]$annotation<-new #swap out the original annotation

q<-ggplot_gtable(pg) #reassemble the plot

plot(q) #generate new plot