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

分组柱状图实现每组百分比总和为100%的技术求助

解决ggplot2分组柱状图组内百分比总和100%的问题

你只需要在计算百分比时按purpose分组,就能轻松实现每组内占比总和为100%,不用做复杂的额外统计步骤。这里给你两种简便实现方式:

方式一:在现有代码基础上直接修改(推荐)

直接基于你原来的计数流程,新增按purpose分组的逻辑来计算组内占比:

library(tidyverse)
library(scales)

loans %>% 
  count(purpose = factor(purpose), not.fully.paid = factor(not.fully.paid)) %>% 
  group_by(purpose) %>%  # 核心:按purpose分组,限定百分比计算范围
  mutate(pct = n / sum(n)) %>%  # 计算组内占比,也可以用prop.table(n)
  ungroup() %>%  # 取消分组避免后续绘图异常
  ggplot(aes(x = purpose, y = pct, fill = not.fully.paid, 
             label = percent(pct))) +
  geom_col(position = "dodge") +
  scale_y_continuous(labels = percent) +
  geom_text(position = position_dodge(width = .9), vjust = -0.5, size = 3)

方式二:先统计计数再单独计算百分比

如果你想先拿到分组计数表再处理,也可以这样操作:

# 先获取分组计数,无需手动加Count列
df <- loans %>% 
  group_by(purpose = factor(purpose), not.fully.paid = factor(not.fully.paid)) %>% 
  summarise(n = n(), .groups = "drop")

# 计算组内百分比
df <- df %>% 
  group_by(purpose) %>% 
  mutate(pct = n / sum(n)) %>% 
  ungroup()

# 绘图
ggplot(df, aes(x = purpose, y = pct, fill = not.fully.paid, label = percent(pct))) +
  geom_col(position = "dodge") +
  scale_y_continuous(labels = percent) +
  geom_text(position = position_dodge(width = .9), vjust = -0.5, size = 3)

关键说明:

  • 你之前用prop.table(n)得到整体占比,是因为没有限定分组范围,prop.table()默认对整个数据集的n计算比例;
  • 加上group_by(purpose)后,sum(n)会自动计算每个purpose组的总计数,n/sum(n)自然就是组内的百分比,每组总和会是100%;
  • 用.groups = "drop"或ungroup()是为了清除分组状态,避免后续绘图出现意外问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 22:05:27