AnjaM AnjaM - 3 years ago 179
R Question

How to modify whiskers of a boxplot in ggplot2?

I'll start with an MWE:


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

enter image description here

I'd like to modify the colour of the whiskers, e.g., set it to red. I don't think it's possible to do this directly both
, so this is my workaround:


stat_sum_df <- function(fun, geom = "crossbar", ...) {
stat_summary( = fun, geom = geom, width = 0.4, ...)

p + stat_boxplot(geom = 'linerange', colour = "red", position = "dodge) +
stat_sum_df("median_hilow", = 0.5, position = "dodge")

enter image description here

The line ranges are stacked on top of each other. So next try:

p + stat_boxplot(geom = 'linerange', colour = "red", position = position_dodge(width = .5)) +
stat_sum_df("median_hilow",, position = position_dodge(width = .5))

enter image description here

Looks nicer, but now there is a fixed space between the boxes (compare cyl = 8 on first and third plot). As I'm going to use this code for different number of levels of
(of course in my real data, it's not
), I don't know in advance how wide the boxes themselves will be, so I can't set a fixed
for the
without specifying a fixed
for the boxes.

Is there a way either to selectively modify whiskers of a
or to adjust space between
elements according to space between the boxes?

Answer Source

How about plotting two boxplots on top of each other. One with red lines and a second one on top without any wiskers at all.

p + geom_boxplot(color="red") + geom_boxplot(aes(ymin=..lower.., ymax=..upper..)) 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download