You need to enable JavaScript to run this app. ggplot2分组直方图添加分箱内组占比标签(单分箱占比和为100%)
优惠活动
大模型
产品
解决方案
定价
更多

ggplot2分组直方图添加分箱内组占比标签(单分箱占比和为100%)

问题根源

你当前代码里的占比计算逻辑..count../sum(..count..)存在本质偏差:这里的sum(..count..)是对整张图所有分箱、所有分组的计数做全局求和,最终算出来的是单个细分块的数量占全数据集总样本的比例,所有细分块的占比加总才会等于100%,完全没有按照单个分箱的维度做组内占比计算,自然达不到每个分箱内各组占比和为100%的效果。

调整方案

在ggplot体系下有两种可落地的实现方式,都可以达到单分箱内组占比合计100%的效果:

方案1:提前预处理分箱统计值(逻辑透明易调试)

先按照绘图的分箱规则切分数据、计算每个分箱下各分组的计数与组内占比,再用堆叠柱状图替代原生直方图,结果完全可控:

library(tidyverse)
# 1. 匹配ggplot默认直方图的分箱边界,避免后续绘制的柱子和原生hist分箱错位
build_bin <- ggplot_build(ggplot(mtcars, aes(x = qsec)) + geom_histogram(bins = 30))
bin_breaks <- build_bin$panel$ranges[[1]]$x.breaks_out[seq_along(build_bin$data[[1]]$x)]

# 2. 切分箱、分组计数、计算单分箱内的组占比
mtcars_bin_stat <- mtcars %>% 
  mutate(qsec_bin = cut(qsec, breaks = bin_breaks, include.lowest = TRUE)) %>% 
  group_by(qsec_bin, am, .drop = FALSE) %>% 
  summarise(block_count = n(), .groups = "drop") %>% 
  # 核心逻辑:以单个分箱为分组单位,计算当前块占比的分母是整个分箱的总计数
  group_by(qsec_bin) %>% 
  mutate(
    block_prop = block_count / sum(block_count),
    # 计算分箱中心x坐标,和直方图的柱子位置对齐
    x_center = as.numeric(qsec_bin) + diff(bin_breaks)[1]/2
  )

# 3. 绘图输出
ggplot(mtcars_bin_stat, aes(x = x_center, y = block_prop, fill = factor(am))) +
  geom_col(width = diff(bin_breaks)[1], alpha = 0.35, col = NA) +
  geom_text(aes(label = scales::percent(block_prop, accuracy = 1)), 
            position = position_stack(vjust = 0.5)) +
  scale_y_continuous(labels = scales::percent, limits = c(0, 1)) +
  scale_fill_discrete(name = "变速箱类型", labels = c("自动", "手动"))

方案2:纯图层内统计计算(无需提前处理数据)

通过after_stat调用分箱统计结果,按分箱中心位置分组计算占比,不需要提前修改原始数据:

ggplot(mtcars, aes(x = qsec, fill = factor(am))) +
  # 核心逻辑:按分箱中心x做分组,取同个x下的总计数当分母算占比
  geom_histogram(
    aes(y = after_stat(count / tapply(count, x, sum)[as.character(x)])),
    col = NA, alpha = 0.35
  ) +
  # 标签计算逻辑和柱子完全对齐
  stat_bin(
    aes(
      y = after_stat(count / tapply(count, x, sum)[as.character(x)]),
      label = after_stat(
        scales::percent(count / tapply(count, x, sum)[as.character(x)], accuracy = 1)
      )
    ),
    geom = "text", position = position_stack(vjust = 0.5)
  ) +
  scale_y_continuous(labels = scales::percent, limits = c(0, 1))

两种方法最终输出的图中,每个分箱对应的堆叠柱总高度为100%,每个块上的标签显示当前组在对应分箱内的占比,完全匹配“分箱1展示20%/80%、分箱2展示30%/70%”的预期效果。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.20 14:54:07