1
votes

Let's consider a boxplot with ggplot:

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

I want the boxes to be filled with a plain color that depends on the mean value of the mpg, for instance from blue to red. I have played with the various group and fill arguments but using "mean(mpg)" always returned the global mean.

2

2 Answers

4
votes

Try this (to fill the boxes with rounded mean values of each cyl group):

mtcars$mean <- as.factor(round(ave(mtcars$mpg, as.factor(mtcars$cyl), FUN=mean)))
ggplot(mtcars, aes(factor(cyl), mpg, fill=mean)) + geom_boxplot()

enter image description here

3
votes

You could create a new column that would then be used for the fill.

library(dplyr)
library(ggplot2)
mtcars%>%
  group_by(cyl)%>%
  mutate(mean_cyl=mean(mpg))%>%
  ggplot(aes(factor(cyl),mpg))+geom_boxplot(aes(fill=mean_cyl))+scale_fill_gradient(low="blue",high = "red")