如何在箱线图上绘制加权平均值?

3

在寻找解决方案和尝试之后,我正在寻求帮助,尝试在箱线图上显示加权平均值(我也尝试将此发布到ggplot2邮件列表)。

以下是一个玩具示例。

#data

value <- c(5, 7, 8, 6, 7, 9, 10, 6, 7, 10)
category <- c("one", "one", "one", "two", "two", "two",
              "three", "three", "three","three")
weight <- c(1, 1.2, 2, 3, 2.2, 2.5, 1.8, 1.9, 2.2, 1.5)
df <- data.frame(value, category, weight)

#unweighted means by category
ddply(df, .(category), summarize, mean=round(mean(value, na.rm=TRUE), 2))

  category mean
1      one 6.67
2    three 8.25
3      two 7.33

#weighted means by category
ddply(df, .(category), summarize, 
          wmean=round(wtd.mean(value, weight, na.rm=TRUE), 2))

  category wmean
1      one  7.00
2    three  8.08
3      two  7.26

#unweighted means added to boxplot (which works fine)
ggplot(df, aes(x = category, y = value, weight = weight)) + 
   geom_boxplot(width=0.6,  colour = I("#3366FF")) + 
   stat_summary( fun.y ="mean", geom ="point", shape = 23, 
                 size = 3, fill ="white") 

我的问题是,如何在箱线图上显示加权平均值而不是未加权平均值?


只是为了澄清给未来的读者:箱线图中的线是中位数,而geom_point可以配置为呈现均值或加权均值,如下面的答案所示。 - Arthur Yip
1个回答

5
你可以将加权均值保存为新的数据框,然后使用它来绘制 geom_point()。参数 inherit.aes=FALSE 将确保点被绘制时不会继承在 ggplot() 调用中提供的信息。
library(Hmisc)
library(plyr)
library(ggplot2)
df.wm<-ddply(df, .(category), summarize, 
             wmean=round(wtd.mean(value, weight, na.rm=TRUE), 2))

ggplot(df, aes(x = category, y = value, weight = weight)) + 
  geom_boxplot(width=0.6,  colour = I("#3366FF")) + 
  geom_point(data=df.wm,aes(x=category,y=wmean),shape = 23, 
             size = 3, fill ="white",inherit.aes=FALSE)

enter image description here


1
这正是医生所开的药方。非常感谢!这非常有帮助。 - user2317662
由于某些原因,我使用这段代码时出现了错误,但是这个问题中的代码可以正常工作。 - Tom

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接