Tukeys post-hoc on ggplot boxplot

前端 未结 1 693
迷失自我
迷失自我 2020-12-10 21:20

Ok, so I think I\'m pretty close with this, but I\'m getting an error when I try to construct my box plot at the end. My goal is to place letters denoting statistical relati

相关标签:
1条回答
  • 2020-12-10 22:07

    I think I found the tutorial you are following, or something very similar. You would probably be best to copy and paste this whole thing into your work space, function and all, to avoid missing a few small differences.

    Basically I have followed the tutorial (http://www.r-graph-gallery.com/84-tukey-test/) to the letter and added a few necessary tweaks at the end. It adds a few extra lines of code, but it works.

    generate_label_df <- function(TUKEY, variable){
    
      # Extract labels and factor levels from Tukey post-hoc 
      Tukey.levels <- TUKEY[[variable]][,4]
      Tukey.labels <- data.frame(multcompLetters(Tukey.levels)['Letters'])
    
      #I need to put the labels in the same order as in the boxplot :
      Tukey.labels$treatment=rownames(Tukey.labels)
      Tukey.labels=Tukey.labels[order(Tukey.labels$treatment) , ]
      return(Tukey.labels)
    }
    
    model=lm(WaterConDryMass$dmass~WaterConDryMass$ChillTime )
    ANOVA=aov(model)
    
    # Tukey test to study each pair of treatment :
    TUKEY <- TukeyHSD(x=ANOVA, 'WaterConDryMass$ChillTime', conf.level=0.95)
    
    labels<-generate_label_df(TUKEY , "WaterConDryMass$ChillTime")#generate labels using function
    
    names(labels)<-c('Letters','ChillTime')#rename columns for merging
    
    yvalue<-aggregate(.~ChillTime, data=WaterConDryMass, mean)# obtain letter position for y axis using means
    
    final<-merge(labels,yvalue) #merge dataframes
    
    ggplot(WaterConDryMass, aes(x = ChillTime, y = dmass)) +
      geom_blank() +
      theme_bw() +
      theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) +
      labs(x = 'Time (weeks)', y = 'Water Content (DM %)') +
      ggtitle(expression(atop(bold("Water Content"), atop(italic("(Dry Mass)"), "")))) +
      theme(plot.title = element_text(hjust = 0.5, face='bold')) +
      annotate(geom = "rect", xmin = 1.5, xmax = 4.5, ymin = -Inf, ymax = Inf, alpha = 0.6, fill = "grey90") +
      geom_boxplot(fill = 'green2', stat = "boxplot") +
      geom_text(data = final, aes(x = ChillTime, y = dmass, label = Letters),vjust=-3.5,hjust=-.5) +
      geom_vline(aes(xintercept=4.5), linetype="dashed") +
      theme(plot.title = element_text(vjust=-0.6))
    

    0 讨论(0)
提交回复
热议问题