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

如何在R的ggplot2中叠加geom_bar?实现0与1计数的堆叠展示

解决堆叠柱状图:0的计数底层,1的计数上层

嘿,我懂你想要的效果——做一个堆叠柱状图,把所有0的计数放在柱子底层,再把1的计数叠在它上面对吧?咱们来一步步搞定这个需求~

首先,咱们得先把你的数据整理成ggplot2能轻松处理的格式,然后再绘图。

步骤1:数据预处理

你的var是一串0和1的向量,首先咱们要统计它们的频数,还要确保0的类别排在前面(这样堆叠时它会在底层):

library(ggplot2)
library(dplyr) # 用它处理数据更顺手

# 你的原始数据
var <- c(0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1)

# 统计频数并转换成数据框,同时指定类别顺序
count_df <- as.data.frame(table(var)) %>%
  rename(category = var, count = Freq) %>%
  mutate(category = factor(category, levels = c("0", "1"))) # 强制0在前,保证堆叠时在底层

如果不想用dplyr,用基础R也能搞定:

# 基础R版本的数据处理
count_table <- table(var)
count_df <- data.frame(
  category = names(count_table),
  count = as.numeric(count_table),
  stringsAsFactors = FALSE
)
count_df$category <- factor(count_df$category, levels = c("0", "1"))

步骤2:绘制堆叠柱状图

接下来用ggplot2绘制堆叠图,核心是用geom_col(position = "stack"),并且把x轴设为一个固定值(比如"总数"),这样就会生成一个单柱子的堆叠图:

ggplot(count_df, aes(x = "总数", y = count, fill = category)) +
  geom_col(position = "stack", width = 0.5) + # 堆叠模式,设置柱子宽度
  scale_fill_manual(values = c("0" = "#4287f5", "1" = "#f54242")) + # 自定义颜色,方便区分两层
  geom_text(aes(label = count), position = position_stack(vjust = 0.5)) + # 在每层中间添加数值标签
  labs(title = "0与1的堆叠计数", x = "", y = "计数", fill = "类别") +
  theme_minimal() # 用清爽的主题优化视觉效果

关键说明

  • 把category转换成因子并指定levels是核心!这样ggplot才会按照你想要的顺序堆叠——0在底层,1在上方。
  • position = "stack"是ggplot2堆叠柱状图的默认模式,明确写出来更直观。
  • 添加geom_text可以让每层的计数数值显示在柱子里,数据展示更清晰。

这样你就能得到完全符合需求的堆叠柱状图啦~

内容的提问来源于stack exchange,提问作者DavideChicco.it

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:22:29