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

如何用ggplot绘制双因子堆叠百分比柱状图?

ggplot绘制按轮次分组的yes/no占比堆叠柱状图

基于原始数据集的实现方法

核心是利用geom_bar()的position = "fill"参数自动按分组计算占比,无需手动统计:

  • 先确保round和variable1为因子类型(避免被当作连续变量处理)
  • position = "fill"会将每个轮次的总高度设为1(对应100%),堆叠部分的高度即为该轮次内yes/no的占比
  • 通过scales::percent_format()将y轴小数转换为百分比格式

代码示例:

library(ggplot2)
library(scales)

# 替换为你的真实原始数据集
raw_data <- data.frame(
  round = factor(sample(1:4, 500, replace = TRUE)),
  variable1 = factor(sample(c("yes", "no"), 500, replace = TRUE))
)

ggplot(raw_data, aes(x = round, fill = variable1)) +
  geom_bar(position = "fill", width = 0.7) +
  scale_y_continuous(labels = percent_format()) +
  labs(
    x = "轮次",
    y = "占比",
    fill = "结果",
    title = "各轮次yes/no占比堆叠柱状图"
  ) +
  theme_minimal()

基于已计算占比数据集的实现方法

如果使用你已统计好的占比数据,需要先将数据整理为长格式,再用geom_col()绘制:

library(ggplot2)
library(scales)

# 整理已统计的占比数据(补充no的占比,总和为100%)
summary_data <- data.frame(
  round = factor(rep(1:4, each = 2)),
  variable1 = rep(c("yes", "no"), 4),
  percentage = c(12.11, 87.89, 14.02, 85.98, 26.59, 73.41, 34.09, 65.91)
)

ggplot(summary_data, aes(x = round, y = percentage, fill = variable1)) +
  geom_col(width = 0.7) +
  scale_y_continuous(labels = percent_format(scale = 1)) + # 因数据为百分比数值,scale设为1
  labs(
    x = "轮次",
    y = "占比",
    fill = "结果",
    title = "各轮次yes/no占比堆叠柱状图"
  ) +
  theme_minimal()

额外提示

  • 若需要自定义yes/no的堆叠顺序,可通过factor(variable1, levels = c("yes", "no"))指定因子水平
  • 调整width参数可以改变柱状图的宽度,让图表更美观

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 03:36:18