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

R语言堆叠条形图:条形顺序调整与数值标签添加问题求助

解决ggplot2堆叠条形图的两个问题:轴顺序与堆叠标签

问题1:调整x轴顺序为First到Fifth

你当前代码里两次修改了inf_episode的顺序:先设置因子水平为First到Fifth,但随后用reorder()按行总和重新排序,之后ggplot里又再次调用reorder(),这导致轴顺序被反转。要恢复固定的First到Fifth顺序,只需去掉多余的reorder()操作,保留最初的因子水平设置即可:

# 保留因子水平设置,去掉后续的reorder
inf_source$inf_episode <- factor(inf_source$inf_episode,
                        levels = c("First", "Second", "Third", "Fourth", "Fifth"))

# 数据转换保持不变
md <- reshape2::melt(inf_source, id = c("inf_episode"))

问题2:添加堆叠块的数值标签

使用geom_text()添加标签,配合position_stack(vjust = 0.5)让标签居中显示在每个堆叠块内,同时过滤掉value = 0的情况避免无效标签:

ggplot(data = md, aes(x = inf_episode, y = value, fill = variable)) +
  geom_col() +
  # 添加数值标签,过滤0值,居中显示
  geom_text(aes(label = ifelse(value > 0, value, "")), 
            position = position_stack(vjust = 0.5), size = 3) +
  labs(x = "感染次数", y = "病例数", fill = "感染类型") # 可选:添加轴标签和图例标题

完整修正代码

library(ggplot2)
library(reshape2)

inf_source <- structure(list(inf_episode = c("First", "Second", 
                                     "Third", "Fourth", "Fifth"), Pneumonia = c(16,6,2,0,0), 
                        IAI = c(6,2,0,0,0), SSTI = c(7,0,2,0,0), Bacteremia = c(4,14,8,6,2),
                        Sinusitis =c(14,10,0,0,0), Other =c(8,7,7,4,0),
                        UTI=c(14,13,1,0,0), CDI=c(0,0,3,0,2), Dental=c(1,3,1,0,0), 
                        Colitis=c(2,2,1,0,0), CLABSI=c(0,0,3,0,0)), 
                   .Names = c("inf_episode", "Pneumonia", "IAI", "SSTI", 
                              "Bacteremia", "Sinusitis", "Other", "UTI", "CDI", "Dental", "Colitis", "CLABSI"), 
                   class = "data.frame", row.names = c(NA, 5L))

# 设置固定的因子顺序,不再修改
inf_source$inf_episode <- factor(inf_source$inf_episode,
                        levels = c("First", "Second", "Third", "Fourth", "Fifth"))

md <- melt(inf_source, id = c("inf_episode"))

ggplot(data = md, aes(x = inf_episode, y = value, fill = variable)) +
  geom_col() +
  geom_text(aes(label = ifelse(value > 0, value, "")), 
            position = position_stack(vjust = 0.5), size = 3) +
  theme_minimal() # 可选:优化主题

说明

  • 去掉reorder()后,x轴会严格按照你设置的因子水平First→Second→Third→Fourth→Fifth排列。
  • geom_text()里的ifelse(value > 0, value, "")确保只显示有数值的标签,避免堆叠块为空时出现0。
  • position_stack(vjust = 0.5)让标签垂直居中于每个堆叠块,提升可读性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 14:53:23