You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ggplot的stat_summary_bin中实现加权均值散点分箱图?

解决stat_summary_bin()绘制加权均值分箱散点图的问题

方案1:通过AES映射权重+内置weighted.mean函数

直接在aes中映射权重变量,利用stat_summary_bin的分组特性,将分箱内的权重传递给weighted.mean计算:

dat <- data.frame(depVar = rnorm(100), expVar = rnorm(100), weightVar = runif(100))

ggplot(dat, aes(x = depVar, y = expVar, weight = weightVar)) +
  stat_summary_bin(
    fun = weighted.mean,
    fun.args = list(w = quote(..weight..), na.rm = TRUE),
    geom = "point"  # 指定绘制散点,可根据需求调整为其他geom
  )
  • 原理:..weight..是stat层自动生成的变量,代表当前分箱内的权重子集;fun.args用于给weighted.mean传递权重参数w,同时开启na.rm处理缺失值。

方案2:自定义分箱统计函数(更灵活)

如果需要精细控制分箱后的x/y计算逻辑,可使用fun.data参数自定义函数,直接从分箱子数据框中提取变量计算:

dat <- data.frame(depVar = rnorm(100), expVar = rnorm(100), weightVar = runif(100))

# 自定义函数:接收分箱子数据框,返回包含加权均值的结果
calc_weighted_bin <- function(df) {
  data.frame(
    x = median(df$depVar),  # 用分箱中位数作为x坐标,也可替换为mean或分箱中点
    y = weighted.mean(df$expVar, df$weightVar, na.rm = TRUE),
    ymin = NA, ymax = NA  # 若不需要置信区间,保留空值即可
  )
}

ggplot(dat, aes(x = depVar, y = expVar)) +
  stat_summary_bin(
    fun.data = calc_weighted_bin,
    geom = "point"
  )

关键疑问解答

  1. fun.args的正确用法:用于传递统计函数的额外参数,当函数需要除y外的参数(如权重),可通过quote(..变量名..)引用stat层生成的分组内变量。
  2. AES映射权重是否合理:这是官方推荐的标准方案,ggplot会自动将权重与分箱数据绑定,确保每个分箱使用对应的权重子集计算。
  3. 多参数函数的适配:要么通过AES映射额外变量并以..变量名..引用;要么使用fun.data自定义函数,直接从分箱子数据框中提取所有所需变量。

内容的提问来源于stack exchange,提问作者ASV

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 04:43:29