I would like to have grouped boxplots which whiskers is defined by stat_summary. With help of changing-whisker-definition I wrote the following code:
# Data
xdf2 <- data.frame(month = rep(1:6,each=100)
, grp = rep(c('A','B'), 50*6)
)
xdf2$m <- rpois(n=nrow(xdf2),10)
# Definition of whiskers
f <- function(x) {
r <- quantile(x, probs = c(0.10, 0.25, 0.5, 0.75, 0.90))
names(r) <- c("ymin", "lower", "middle", "upper", "ymax")
r
}
# Add points outside of whiskers
o <- function(x) {
subset(x, x < quantile(x,probs=0.1) | quantile(x,probs=0.9) < x)
}
# Plot
ggplot(data = xdf2
, aes(factor(month),m, color=grp)
) +
stat_summary(fun.data = f
, geom="boxplot"
, position=position_dodge(width=1)
, size=1
) +
stat_summary(fun.y = o, geom="point", position=position_dodge(width=1)) +
scale_color_manual(values = c("gray30","darkgrey"),labels = c("AAA","BBB")) +
theme_bw()
which gives the following graphs:
There are some changes I would like to perform:
- How can I change the width of the boxes?
- How can I fill the boxes with the same color of the border?
I would be happy for any help. Thanks a lot.
Map
fill
aesthetic togrp
and add a similar scale for it. I'm using slightly different colours to make the mean visible.To change boxplot widths, use
ggsave
with variouswidth
parameters, boxplots will be adjusted automatically. If you would like to add some space in between, you'll have to cheat a bit, see below.It is not easy to modify width in conjunction with
stat_summary
: though there is awidth
parameter forgeom_bar
andgeom_boxplot
, I couldn't make it work properly withstat_summary
. Instead, I'm using some dirty tricks withscale_x
.Play around
width
inposition_dodge
for additional adjustment.