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

ggplot2百分比堆叠柱状图绘制失败,求解决方法

解决ggplot百分比堆叠柱状图异常问题

问题根源

你的代码中aes(y=SmokeType)的映射错误:SmokeType是分类变量,geom_col()默认会将其转为整数水平值绘制,但position="fill"需要基于各年份内不同吸烟类型的计数占比计算,分类变量无法支撑这个逻辑,导致图表异常。

两种解决方法

方法1:用stat_count自动计算计数并转换百分比

无需提前汇总数据,让stat_count自动统计每组的数量,再通过position="fill"归一化为百分比:

ggplot(data = subset(Cd_no_110, !is.na(SmokeType)), aes(x = Check_Year, fill = SmokeType)) +
  stat_count(position = "fill", geom = "col") +
  scale_y_continuous(labels = scales::percent) +  # 将y轴转为百分比刻度
  labs(y = "百分比")

方法2:提前汇总数据计算百分比(更灵活)

先用dplyr统计各年份各吸烟类型的占比,再绘制堆叠柱状图:

library(dplyr)

# 汇总计算百分比
summary_df <- Cd_no_110 %>%
  filter(!is.na(SmokeType)) %>%
  count(Check_Year, SmokeType) %>%
  group_by(Check_Year) %>%
  mutate(percent = n / sum(n)) %>%
  ungroup()

# 绘制堆叠柱状图
ggplot(summary_df, aes(x = Check_Year, y = percent, fill = SmokeType)) +
  geom_col(position = "stack") +
  scale_y_continuous(labels = scales::percent) +
  labs(y = "百分比")

说明

两种方法都能生成标准的百分比堆叠柱状图,方法1适合快速绘图,方法2便于自定义统计逻辑(比如添加过滤、调整分组规则)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 21:22:11