2020-12-11

How to modify whiskers of a boxplot in ggplot2?

Title

Problem

We want to modify the colour of the whiskers in a boxplot using ggplot2. In our example, the default colour (black) to red.

library(ggplot2)
p <- ggplot(mtcars, aes(factor(cyl), mpg, fill = factor(am)))
p + geom_boxplot()

Solution

  • Option 1
  • We plot error bars in red and then superimpose the boxplots in black.

    library(ggplot)
    p + stat_boxplot(
      geom = "errorbar",
      colour = "red",
      width = 0,
      position = position_dodge(0.75)
    ) +
      geom_boxplot(coef = 0, outlier.shape = NA)
    
  • Option 2
  • We superimpose two boxplots on top of each other. The first one with red borders and the secong one without whiskers in black.

    p + geom_boxplot(color="red") + 
      geom_boxplot(aes(ymin=..lower.., ymax=..upper..)) 
    

References

No hay comentarios:

Publicar un comentario

Nube de datos