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

如何用R为长格式透视数据制作含总计列的比例堆叠条形图

堆叠占比条形图解决方案(含总计列与百分比标签)

问题修正与核心说明

  1. position="fill"报错解决:该参数是geom_bar()的配置参数,不属于美学映射(aes())范畴,直接放在geom_bar()括号内即可,不要放入aes()中。
  2. 总计列实现:将原始数据复制一份,把CASE字段改为"Total"后合并到原数据集,即可生成单独的总计分组。
  3. 百分比标签添加:利用stat="count"自动统计每组计数,计算组内占比后生成标签,通过position_fill()让标签居中显示在堆叠块内。

完整代码

# 加载所需包
library(tidyverse)

# 你的原始数据集
ownership <- structure(list(SPROP = c(100L, 0L, 0L, 70L, 6L, 0L, 0L, 0L, 10L, 
45L, 100L), SARREN = c(0L, 100L, 100L, 20L, 94L, 100L, 100L, 
100L, 90L, 55L, 0L), SCED = c(0L, 0L, 0L, 10L, 0L, 0L, 0L, 0L, 
0L, 0L, 0L), CASE = c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
2L)), row.names = 10:20, class = "data.frame")

# 转换为长格式,筛选每个样本对应的类别
ownership_long <- ownership %>%
  pivot_longer(cols = c(SPROP, SARREN, SCED), names_to = "variable", values_to = "value") %>%
  filter(value == 100) %>%  # 仅保留样本所属的类别(值为100的行)
  mutate(CASE = as.factor(CASE))

# 合并总计分组数据
ownership_long_with_total <- ownership_long %>%
  bind_rows(
    ownership_long %>% mutate(CASE = "Total")
  )

# 绘制带百分比标签的占比堆叠条形图
ggplot(ownership_long_with_total, aes(x = CASE, fill = variable)) +
  geom_bar(position = "fill") +  # 正确设置占比堆叠
  geom_text(
    stat = "count",
    aes(label = paste0(round((..count../sum(..count..))*100, 1), "%")),
    position = position_fill(vjust = 0.5)  # 标签居中对齐
  ) +
  scale_y_continuous(labels = scales::percent_format()) +  # Y轴显示百分比格式
  labs(
    x = "案例",
    y = "占比",
    fill = "变量"
  ) +
  theme_minimal()

关键细节解释

  • 数据转换:通过pivot_longer将宽格式转为长格式,筛选值为100的行,避免无效的0值干扰统计结果。
  • 总计列:通过bind_rows合并原数据与修改CASE为"Total"的副本,实现单独的总计分组展示。
  • 百分比计算:利用stat="count"的内置变量..count..,自动计算每个类别在对应分组(案例/总计)中的占比,生成带百分比符号的标签。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 07:53:22