Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading