You could do like this: First, calculate the median
, first and third quartile (quart1
and quart3
) for ToothGrowth
, grouped by supp
and dose
. Afterwards you can fill in the lower and upper rectangles of the boxplots. Since you wanted four different colors, I added four different rectangles.
ToothGrowth <- ToothGrowth %>% mutate(dose = factor(dose)) %>% group_by(supp, dose) %>%
mutate(median = median(len), quart1 = quantile(len, 0.25), quart3 = quantile(len, 0.75))
ggplot(ToothGrowth, aes(dose, len)) +
geom_boxplot(width = 0.6) +
facet_grid(~supp) +
geom_rect(data = subset(ToothGrowth, supp == "OJ"),
aes(xmin = as.numeric(dose) - 0.3, xmax = as.numeric(dose) + 0.3, ymin = quart1, ymax = median),
fill = "#008AA7", color = "black") +
geom_rect(data = subset(ToothGrowth, supp == "VC"),
aes(xmin = as.numeric(dose) - 0.3, xmax = as.numeric(dose) + 0.3, ymin = quart1, ymax = median),
fill = "#005645", color = "black") +
geom_rect(data = subset(ToothGrowth, supp == "OJ"),
aes(xmin = as.numeric(dose) - 0.3, xmax = as.numeric(dose) + 0.3, ymin = median, ymax = quart3),
fill = "#A2EFFD", color = "black") +
geom_rect(data = subset(ToothGrowth, supp == "VC"),
aes(xmin = as.numeric(dose) - 0.3, xmax = as.numeric(dose) + 0.3, ymin = median, ymax = quart3),
fill = "#90AC9E", color = "black")
Which gives the following plot:
