ggplot2在分组数据的框图中显示单独的平均值

时间:2014-05-29 20:49:48

标签: r mean ggplot2 boxplot

我想为分组数据创建一个框图,将每个组的平均值显示为框中的一个点。使用以下代码,我只得到两个组的单点。

df <- data.frame(a=factor(rbinom(100, 1, 0.45), label=c("m","w")), 
    b=factor(rbinom(100, 1, 0.3), label=c("young","old")),
    c=rnorm(100))
ggplot(aes(y = c, x = b, fill = a), data = df) + 
    geom_boxplot() +
    stat_summary(fun.y="mean", geom="point", shape=21, size=5, fill="white")

enter image description here

2 个答案:

答案 0 :(得分:7)

问题的一部分是改变点的填充,因为填充是确定应绘制两​​个不同颜色的箱形图的属性,该点的行为就好像只有一个组一样。我认为这应该给你你想要的东西。

ggplot(df, aes(x=b, y=c, fill=a)) +
  geom_boxplot() +
  stat_summary(fun.y="mean", geom="point", size=5,
    position=position_dodge(width=0.75), color="white")

box plot with mean

答案 1 :(得分:0)

不确定这是否是最有效的方法。

首先,您可以使用a创建一个虚拟数据集,其中包含每b aggregategeom_point的均值 然后,将其解析为position_dodge(width=.75)并添加dodge,其似乎与geom_boxplot

中的默认library(ggplot2) df <- data.frame(a=factor(rbinom(100, 1, 0.45), label=c("m","w")), b=factor(rbinom(100, 1, 0.3), label=c("young","old")), c=rnorm(100)) means <- aggregate(c ~ a + b, df, mean) ggplot(aes(y = c, x = b, fill = a), data = df) + geom_boxplot() + geom_point(data = means, aes(y = c, x = b), position=position_dodge(width=.75), color = "white") 相匹配
{{1}}

enter image description here