How to generate a boxplot graph with whisker by ggplot

ggplot2

#1

Is it possible to create a boxplot graph with whisker? Thank you!
Here is a sample code, the generated boxplot without whisker.

library(ggplot2)
ggplot(data=mpg, mapping=aes(x=class, y=hwy)) + geom_boxplot()


#2

When I run that code, the boxplots do have whiskers (as expected, since whiskers are created by default for geom_boxplot()):

Just to be clear, by “whiskers” I mean the lines extending from the top and bottom of the boxes. Is this what your plot looks like? If so, can you give an example of how you want it to look instead?


#3

Thank you for your response!

The whisker is horizontal line at 1.5 IQR of the upper quartile/lower quartile, if using boxplot, whisker will display, but ggplot can contol much more other parameters, I like to use ggplot.

attach(mtcars)
boxplot(vs, disp)


#4

Hi there,

If you add stat_boxplot(geom = 'errorbar') you'll get what you want. Compare a (your code) to b (your code augmented with stat_boxplot() ) below:

library(tidyverse)
library(gridExtra)
#> 
#> Attaching package: 'gridExtra'
#> The following object is masked from 'package:dplyr':
#> 
#>     combine

a <- ggplot(data=mpg, mapping=aes(x=class, y=hwy)) + geom_boxplot()
b <- ggplot(data=mpg, mapping=aes(x=class, y=hwy)) + geom_boxplot() + stat_boxplot(geom = 'errorbar')

grid.arrange(a, b, nrow = 2)

Created on 2018-10-04 by the reprex package (v0.2.0).

Hope this helps!


#5

A minor iteration on @kmprioli’s answer: if you create the errorbar layer first, then it will appear behind the boxplot layer:

ggplot(data=mpg, mapping=aes(x=class, y=hwy)) + 
  stat_boxplot(geom = "errorbar", width = 0.2) + 
  geom_boxplot()

As a note, the “whiskers” are traditionally the vertical lines. The crossbars may or may not be present (they weren’t included Tukey’s original design, see http://mathworld.wolfram.com/Box-and-WhiskerPlot.html).


#6

Thank you so much! it works.


#7

Thank you!!!!!!!!!!!!!!!!!!!!111
Great! it works.


#8

As a note for the future, there was a follow-up question (involving box plots with more than one group) here: