How to change box mustache in ggplot2?

I will start with MWE:

library(ggplot2)

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

enter image description here

I would like to change the color of the mustache, for example, set it to red. I don’t think it’s possible to do it directly like geom_boxplotso this is my workaround:

library(Hmisc)

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

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

enter image description here

Ranges of lines are stacked on top of each other. So the following attempt:

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

enter image description here

It looks better, but now there is a fixed space between the drawers (compare cyl = 8 in the first and third plot). Since I am going to use this code for a different number of levels am(of course, this is not in my real data am), I don’t know in advance how wide the boxes themselves will be, so I can’t set fixed widthfor linerangewithout specifying fixed widthfor fields.

boxplot linerange ?

+4
2

, . - .

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

, - :

library(ggplot2)
p + stat_boxplot(geom = "errorbar", colour = "red") + 
  geom_boxplot(coef = 0, outlier.size = 0)

enter image description here

+2

Source: https://habr.com/ru/post/1529204/


All Articles