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

用ggplot2实现堆叠条形图按组及Total值排序并显示总计

解决ggplot2堆叠条形图的分组排序与总计显示问题

问题1:按Group分组并按Total值排序

要实现按Group分组,且每个Group内的Category按Total值排序,需基于原始数据集的Total字段固定Category的因子顺序——先按Group分组,再在组内按Total降序排列:

# 调整Category的排序规则:按Group分组,组内按Total降序
dat <- dat %>%
  arrange(Group, desc(Total)) %>%
  mutate(Category = factor(Category, levels = Category))

# 重新生成用于绘图的长格式数据
dfm <- melt(dat, id.vars = c("Category", "Group")) %>% 
  filter(variable %in% c("Value1", "Value2"))

通过将Category转换为指定顺序的因子,后续绘图时会自动遵循「Group分组+组内Total降序」的排列逻辑。

问题2:在堆叠条形图右侧显示总计数值

直接调用原始数据集的Total字段,新增一个geom_text层,将总计值偏移到条形右侧显示。注意因使用coord_flip()翻转了坐标轴,需调整y轴偏移量避免文本与条形重叠:

ggplot(dfm, aes(x = Category, y = value, fill = variable)) +
  geom_col() +
  # 添加总计文本:基于原始dat的Total数据,偏移至条形外侧
  geom_text(data = dat, aes(y = Total + 2, label = Total), size = 3) +
  coord_flip() +
  theme_bw() +
  geom_text(aes(label = value), position = position_stack(vjust = 0.5), size = 3)

其中y = Total + 2的偏移量可根据图表实际大小自行调整,确保文本显示清晰。

完整可运行代码

library(dplyr)
library(reshape2)
library(ggplot2)

dat <- read.csv(textConnection(
  "Category,Value1,Value2,Total,Group
A,10,10,20,1
B,20,30,50,1
C,5,2,7,1
D,5,10,15,2
E,10,20,30,2
F,30,4,34,2"))

# 处理Category排序
dat <- dat %>%
  arrange(Group, desc(Total)) %>%
  mutate(Category = factor(Category, levels = Category))

# 转换为长格式数据
dfm <- melt(dat, id.vars = c("Category", "Group")) %>% 
  filter(variable %in% c("Value1", "Value2"))

# 绘制最终图表
ggplot(dfm, aes(x = Category, y = value, fill = variable)) +
  geom_col() +
  geom_text(data = dat, aes(y = Total + 2, label = Total), size = 3) +
  coord_flip() +
  theme_bw() +
  geom_text(aes(label = value), position = position_stack(vjust = 0.5), size = 3)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 15:25:58