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

R语言ggplot堆叠柱状图:如何将数据标签置于柱顶?

解决堆叠柱状图柱顶标签位置问题

问题根源

你当前的代码有两个核心问题:

  1. 坐标尺度不匹配:freq里的f是百分比数值(如10、20),但y轴是转诊绝对数量(0-2250),用百分比数值作为标签的y坐标,自然无法对齐柱顶的绝对数位置。
  2. 语法错误:mutate里的括号嵌套错误、scale_fill_manual的labels未用向量包裹、scale_y_continuous缺少闭合括号,这些都会导致代码运行异常或显示错误。

修正后的代码方案

方案一:提前计算总数据,精准定位标签

先计算每个民族的总转诊数和占比,再将标签放在总数量对应的y轴位置:

# 计算每个民族的总转诊数及占比
total_stats <- df %>%
  group_by(ethnicity) %>%
  summarise(total_referrals = n(),
            pct = round(total_referrals / sum(total_referrals) * 100, 1))

# 准备堆叠图所需的分组数据
plot_data <- df %>%
  group_by(pathway, ethnicity) %>%
  count(name = "referral_count")

# 绘图
ggplot(plot_data, aes(x = ethnicity, y = referral_count, fill = pathway)) +
  geom_bar(stat = "identity", position = "stack") +
  # 添加柱顶占比标签,y值用总转诊数,vjust向上偏移避免遮挡
  geom_text(data = total_stats, 
            aes(x = ethnicity, y = total_referrals, label = paste0(pct, "%")),
            inherit.aes = FALSE,
            vjust = -0.5) +
  theme(legend.position = "bottom") +
  scale_fill_manual(name = "",
                    values = c("lightblue", "deepskyblue4"),
                    labels = c("a", "b")) +
  xlab("") +
  ylab("Number of Referrals") +
  scale_y_continuous(breaks = seq(0, 2250, 250), expand = c(0, 0))

方案二:用stat_summary自动计算总和(无需额外数据框)

直接在ggplot中通过stat_summary计算每个民族的总转诊数,同时生成占比标签:

df %>%
  group_by(pathway, ethnicity) %>%
  count(name = "referral_count") %>%
  ggplot(aes(x = ethnicity, y = referral_count, fill = pathway)) +
  geom_bar(stat = "identity", position = "stack") +
  # 自动计算每个x的总和,生成占比标签
  stat_summary(
    fun = sum,
    aes(label = paste0(round(..y../sum(..y..)*100, 1), "%")),
    geom = "text",
    vjust = -0.5,
    inherit.aes = FALSE
  ) +
  theme(legend.position = "bottom") +
  scale_fill_manual(name = "",
                    values = c("lightblue", "deepskyblue4"),
                    labels = c("a", "b")) +
  xlab("") +
  ylab("Number of Referrals") +
  scale_y_continuous(breaks = seq(0, 2250, 250), expand = c(0, 0))

关键说明

  • 用vjust = -0.5让标签在柱顶上方偏移一点,避免和柱子边缘重合;
  • 标签内容用paste0(pct, "%")显示带百分号的占比,更直观;
  • 修正了所有语法错误,确保代码能正常运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 02:46:23