Add p value or asterisk to ggplot

Andre Elrico picture Andre Elrico · Feb 27, 2018 · Viewed 9.2k times · Source

What I want is the pairwise comparison with for eg paired Wilcox-test. With the groups: list(c("0.5", "1"),c("1","2"),c("2","3")). Very plain and simple at first no alpha correction and so on.

Code:

data_summary <- function(data, varname, groupnames){
    require(plyr)
    summary_func <- function(x, col){
        c(mean = mean(x[[col]], na.rm=TRUE),
          sd = sd(x[[col]], na.rm=TRUE))
    }
    data_sum<-ddply(data, groupnames, .fun=summary_func,
                    varname)
    data_sum <- rename(data_sum, c("mean" = varname))
    return(data_sum)
}

    df_long <- rbind(ToothGrowth[,-2],data.frame(len=40:50,dose=3.0))
    df_long$ID <- data.table::rowid(df_long$dose)
    df_aggre<- data_summary(df_long, varname="len", 
                        groupnames=c("dose"))

    p<-
    ggplot(df_aggre, aes(x=dose, y=len)) +
        geom_errorbar(aes(ymin=len-sd, ymax=len+sd), width=.1) +
        geom_line() + geom_point() + theme_minimal()

Desired Output. (I want the stuff in the red circles!)

image with sign added

(The statistical results (eg. ns, , *) are invented)

My try:

library(ggpubr)
p + stat_compare_means(data=df_long,mapping=aes(x=dose, y=len),label = "p.signif", method= "wilcox.test", comparisons=list(c("0.5","1"),c("1","2"),c("2","3")))

    #Error in f(...) : 
    #Can only handle data with groups that are plotted on the x-axis

Answer

User 6683331 picture User 6683331 · Feb 27, 2018

An easy way could be to add manually the notations:

  p + annotate("text", x = 0.5, y = 23, label = "ns") +
  annotate("text", x = 1.5, y = 30, label = "**") +
  annotate("text", x = 2.5, y = 48, label = "***")