rggplot2anovamultcompview

Displaying compact letter display (CLD) from 2-way ANOVA in a boxplot


I used multcompLetters4() to obtain the compact letter display from a two-way ANOVA performed on 4 groups and I am now trying to display my data and the letters as a boxplot. This is the code I used :

Data

data1 <- structure(list(Tx = c("T", "T", "T", "T", "T", "T", "T", "T", 
"T", "T", "E", "E", "E", "E", "E", 
"E", "E", "E", "E", "E", "T", "T", 
"T", "T", "T", "T", "T", "T", "T", "E", "E", "E", 
"E", "E", "E", "E", "E", "E", 
"E"), Group = c("I", "I", "I", "I", "I", "I", 
"I", "I", "I", "I", "I", "I", "I", "I", "I", "I", "I", 
"I", "I", "I", "G", "G", "G", "G", "G", "G", "G", "G", 
"G", "G", "G", "G", "G", "G", "G", "G", "G", "G", "G"
), Nb = c(24, 
21, 13, 18, 11, 12, 10, 17, 22, 13, 3, 6, 12, 11, 1, 5, 10, 10, 
10, 2, 18, 15, 15, 16, 19, 16, 22, 23, 19, 11, 10, 11, 16, 5, 
15, 14, 14, 17, 16)),  class = c("tbl_df", "tbl", 
"data.frame"), row.names = c(NA, -39L))

Obtaining the letters and plotting

aov1 <- aov(Nb~Tx*Group, data=data1)

tukey <- TukeyHSD(aov1)

tukey.cld <- multcompLetters4(aov1, tukey)
cld <- as.data.frame.list(tukey.cld$`Tx:Group`)
cld

summary <- data1 %>%
  group_by(Tx,Group) %>%
  summarise(
    w=mean(Nb),
    sd=sd(Nb),
    max=max(Nb)) %>% 
  arrange(desc(w)) 

summary$Tukey <- cld$Letters

ggplot(data1, aes(x = Group, y = Nb, fill = Tx)) +
  geom_boxplot(show.legend = TRUE, outlier.shape = NA) +
  geom_text(data = summary, aes(x = Group, label = Tukey, y = max), inherit.aes = FALSE)

As seen on the picture, geom_text() can't distinguish the different "Tx", as they are displayed on the same "Group" with no regard for the "Tx". I also tried geom_text(data = summary, aes(x = interaction(Group,Tx)... which doesn't work either.

Is there a way to make geom_text() comprehend that the letters should be displayed in regard to the fill argument ?

enter image description here


Solution

  • enter image description here You can pass a fill argument. and pass a position argument to move the labels away from the center. Also, you can pass a vjust=-1 to move the labels higher.

    ggplot(data1, aes(x = Group, y = Nb, fill = Tx)) +
      geom_boxplot(show.legend = TRUE, outlier.shape = NA) +
      geom_text(data = summary, position=position_dodge(0.8), aes(x = Group,fill=Tx, label = Tukey, y = max), inherit.aes = FALSE)