title: How to order variable in a boxplot with respective tukey test
body: <p>I used the code from r-graph-gallery.com that i adapted to my data.</p>
  
  <p>I would like to do 6 boxplots in one graph and order them in a specific order, but then as I am doing the ordering, the tukey analysis doesn't order itself at the same time with it !</p>
  
  <p>Do you know how I can improve it ?</p>
  
  <p>This is the wrong order but the right tukey test representation :
  <img src="https://i.stack.imgur.com/7PjRG.png" alt="Graph with the wrong order"></p>
  
  <p>And here the one that has the right order but not the right tukey test repartition.
  <img src="https://i.stack.imgur.com/3hxAQ.png" alt="Graph with wrong tukey test position"></p>
  
  <p>What should I do to get the right order for the TUKEY test as well ?</p>
  
  <p>By the way does anyone knows how to get the "a" value for the highest mean of the tukey test and not the "c" ? </p>
  
  <p>Thank you for your help !</p>
  
  <p>Here is the code I used :</p>
  
  <pre><code>date&lt;- (read.delim("SoilOBIoldtd.txt", header=TRUE))
  # library
  library(multcompView)
  # What is the effect of the level on the CEC ?
  model=lm( date$CEC_eff ~ date$level )
  
  ANOVA=aov(model)
  # Tukey test to study each pair of level :
  TUKEY &lt;- TukeyHSD(x=ANOVA, 'date$level', conf.level=0.95)
  #This line is the difference between the two plots (using or ignoring this line)
  date$level &lt;- factor(date$level , levels=c("DAFS_Top", "DAFS_Down",
  "CONV_Top","CONV_Down","Old_cocoa_Top","Old_cocoa_Down"))
  # Tuckey test representation :
  plot(TUKEY , las=1 , col="brown")
  generate_label_df &lt;- function(TUKEY, CEC_eff){
     # Extract labels and factor levels from Tukey post-hoc 
    Tukey.levels &lt;- TUKEY[[CEC_eff]][,4]
    Tukey.labels &lt;- data.frame(multcompLetters(Tukey.levels,reversed = FALSE)['Letters'])
    #I need to put the labels in the same order as in the boxplot :
    Tukey.labels$level=rownames(Tukey.labels)
    Tukey.labels=Tukey.labels[order(Tukey.labels$level) , ]
    return(Tukey.labels)}
  # Apply the function on my dataset
  LABELS &lt;- generate_label_df(TUKEY , "date$level")
  # A panel of colors to draw each group with the same color :
  my_colors &lt;- c(   rgb(143,199,74,maxColorValue = 255),  rgb(242,104,34,maxColorValue = 255),   rgb(111,145,202,maxColorValue = 255))
  # Draw the basic boxplot
  a &lt;-boxplot(date$CEC_eff ~ date$level , ylim=c(min(date$CEC_eff ) , 1.1*max(date$CEC_eff)) , col=my_colors[as.numeric(LABELS[,1])] , ylab="CEC" , main="")
  # I want to write the letter over each box. Over is how high I want to write it.
  over &lt;- 0.1*max( a$stats[nrow(a$stats),] )
  #Add the labels
  text( c(1:nlevels(date$level)) , a$stats[nrow(a$stats),]+over , LABELS[,1]  , col=my_colors[as.numeric(LABELS[,1])] )
  </code></pre>