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

基于多列计数的堆叠柱状图绘制问题(R语言)

多列分类计数的堆叠柱状图绘制方案

步骤1:数据格式转换

要绘制堆叠柱状图,首先得把宽格式数据转成适合统计的长格式,用tidyverse包(包含dplyr和tidyr)即可完成:

# 加载工具包
library(tidyverse)

# 转换数据格式并统计各等级出现次数
count_df <- df %>%
  # 将所有列转为"列名-等级"的长表结构
  pivot_longer(everything(), names_to = "column", values_to = "level") %>%
  # 按列名和等级分组,统计次数
  count(column, level)

转换后的count_df核心结构示例:

columnleveln
aHigh4
bLow2
bMedium2
.........

步骤2:绘制堆叠柱状图

用ggplot2绘制垂直堆叠柱状图,若要转为你需要的水平样式,只需添加coord_flip():

# 垂直堆叠柱状图
ggplot(count_df, aes(x = column, y = n, fill = level)) +
  geom_col(position = "stack") +
  labs(x = "列名", y = "出现次数", fill = "等级") +
  theme_minimal()

# 水平堆叠柱状图(最终目标样式)
ggplot(count_df, aes(x = column, y = n, fill = level)) +
  geom_col(position = "stack") +
  labs(x = "列名", y = "出现次数", fill = "等级") +
  theme_minimal() +
  coord_flip()

完整可运行代码(含示例数据)

如果需要直接验证效果,可使用包含你提供数据的完整代码:

library(tidyverse)

# 构造你提供的示例数据
df <- tibble(
  a = c("High", "High", "High", "High"),
  b = c("Low", "Medium", "Low", "Medium"),
  c = c("High", "Low", "High", "Low"),
  d = c("Medium", "High", "Medium", "High"),
  e = c("Low", "Medium", "Low", "High"),
  f = c("High", "Low", "High", "Medium")
)

# 数据转换与计数
count_df <- df %>%
  pivot_longer(everything(), names_to = "column", values_to = "level") %>%
  count(column, level)

# 绘制水平堆叠柱状图
ggplot(count_df, aes(x = column, y = n, fill = level)) +
  geom_col(position = "stack") +
  labs(x = "列名", y = "出现次数", fill = "等级") +
  theme_minimal() +
  coord_flip()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 06:54:35