labels on the top of a boxplot

Viewed 179

I am trying to make a boxplot like the one in the picture below where it shows Tukey test results above the boxplot. However, my current attempt, everything in the output is okay except when I add the labels over the boxplot when everything disappears.

Example expected output:

The boxplot I want to obtain

Output of code below: The boxplot output of my code

my data imported from excel

treatment   value
C   12.82310
C   12.820478
C   12.825347
ER  8.969508
ER  8.651902
ER  9.226524
EB  7.596646
EB  7.727204
EB  7.627831
V10 8.988685
V10 8.908832
V10 8.827404
EO  9.446098
EO  9.007681
EO  8.843868

the code I tried

library(multcompView)
data=data.frame(Az) 
data
# What is the effect of the treatment on the value? 
model=lm( data$value ~ data$treatment ) 
ANOVA=aov(model)
# Tukey test to study each pair of treatment: 
TUKEY <- TukeyHSD(x=ANOVA, 'data$treatment', conf.level=0.95)
# Tuckey test representation: 
plot(TUKEY , las=1 , col="brown" ) 

# You need to group the treatments that are not different each other together. 
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']) 
  #You 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) 
} 

# Apply the function on my dataset 
LABELS=generate_label_df(TUKEY , "data$treatment") 
LABELS
my_colors=c( rgb(143,199,74,maxColorValue = 255),rgb(242,104,34,maxColorValue = 255), rgb(111,145,202,maxColorValue = 255),rgb(254,188,18,maxColorValue = 255) , rgb(74,132,54,maxColorValue = 255),rgb(236,33,39,maxColorValue = 255),rgb(165,103,40,maxColorValue = 255))

# Draw the basic boxplot 
a=boxplot(data$value ~ data$treatment , ylim=c(min(data$value) , 1.1*max(data$value)) , col=my_colors[as.numeric(LABELS[,1])] , ylab="Concentration (mg/kg)", xlab="Mode de Lavage", main="")
over=0.1*max( a$stats[nrow(a$stats),] )
text(a$stats[nrow(a$stats),c(1:nlevels(data$treatment))]+over , LABELS[,1], col=my_colors[as.numeric(LABELS[,1])] ) 
#Add the Legend 
legend("topright", legend = c("C = Contrôle", "ER = Eau de Robinet", "EB = Eau Bouillante", "V10= Vinaigre 10%", "EO = Eau Ozonisée"), 
       bty = "y", pt.cex = 1, cex = 0.8, horiz = F, inset = 0)
0 Answers
Related