使用 ggplot2 根据它们的平均值为箱线图着色

Color the boxplot according to their mean value with ggplot2

让我们考虑一个带有 ggplot 的箱线图:

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

我希望用取决于 mpg 平均值的纯色填充方框,例如从蓝色到红色。我玩过各种组和填充参数,但使用 "mean(mpg)" 总是返回全局平均值。

您可以创建一个新列,然后用于填充。

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")

试试这个(用每个圆柱组的四舍五入平均值填充方框):

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