Search code examples
rggplot2boxplot

change the colors of the whiskers in ggplot2 boxplot


I am tying to make a boxplot using ggplot2. I can create the boxes, but I want to change the colors of the whiskers in them. Essentially, I want the whiskers to match the colors of the boxes, but keep the median line as black. I'm struggling with how to do this below is my code and my output plot.enter image description here

ggplot(mirtras, aes(x=variable, y=value, fill=Cond)) +
geom_boxplot() +
theme_classic() +
theme_bw() +
theme(plot.title= element_text(hjust=0.5, face= "bold"),
        plot.margin = margin(1,3,1,3, "cm")) +
stat_boxplot(geom ='errorbar') +
scale_fill_manual(values=c("green","blue","red"), name ="condition") +
labs(colour="condition")

Solution

  • Plot colored errorbars first, then draw boxplots without whiskers:

    ggplot(mirtras, aes(x = variable, y = value, fill = Cond)) +
      stat_boxplot(geom = 'errorbar', aes(color = Cond), width = 0.5,
                   position = position_dodge(0.9), linewidth = 1) +
      geom_boxplot(aes(ymax = after_stat(upper), ymin = after_stat(lower)),
                   position = position_dodge(0.9)) +
      scale_fill_manual(values = c("green", "blue", "red"), guide = 'none') +
      scale_color_manual(values = c("green4", "blue", "red2"), guide = 'none') +
      theme_bw() +
      theme(plot.title = element_text(hjust = 0.5, face = "bold"),
            plot.margin = margin(1, 3, 1, 3, "cm"))
    

    enter image description here


    Data used

    There was no data supplied in the question, but the following data set has the same names and approximate values:

    set.seed(1)
    
    mirtras <- data.frame(variable = 'X27',
                          Cond = rep(c('A', 'B', 'C'), times = c(20, 20, 40)),
                          value = c(rnorm(45, 15.5, 0.5), rnorm(35, 19, 0.5)))