You need to enable JavaScript to run this app. ggplot2堆叠条形图如何分别标注分段计数与每个柱的总数值
优惠活动
大模型
产品
解决方案
定价
更多

ggplot2堆叠条形图如何分别标注分段计数与每个柱的总数值

ggplot2堆叠条形图双标注实现方案

实现逻辑

  • 分段内部计数标注:将文字居中嵌入每个堆叠块内部
  • 条形总数值标注:将总数值放在堆叠块最外侧,不遮挡原有内容

完整可运行代码

方式1(稳定易维护:提前预计算总数值)

# 预计算每个Type对应的堆叠总数值
total_summary <- dealflow_summary_fiscal_yr %>%
  dplyr::group_by(Type) %>%
  dplyr::summarise(total = sum(Total))

# 绘图主逻辑
ggplot(dealflow_summary_fiscal_yr, aes(x = Total, y = Type, fill = status)) +
  geom_bar(stat = "identity", width = 0.6) +
  # 分段内部计数标注
  geom_text(aes(label = Total),
            position = position_stack(vjust = 0.5),
            color = "white",
            size = 3) +
  # 总数值标注
  geom_text(data = total_summary,
            aes(x = total, y = Type, label = total),
            inherit.aes = FALSE,
            hjust = -0.2,
            color = "black",
            size = 3.5) +
  # 原有主题与样式设置
  theme_classic() +
  theme(
    axis.line.y = element_blank(),
    axis.ticks = element_blank(),
    legend.position = "bottom",
    axis.text.x = element_text(face = "bold", color = "black", size = 10, angle = 45, hjust = 1)
  ) +
  labs(x = "", y = "", fill = "") +
  scale_fill_manual(values = c("#284a8d", "#00B5CE")) +
  # 扩展x轴右边界,避免总数值标注被截断
  scale_x_continuous(expand = expansion(mult = c(0, 0.1)))

方式2(无需预处理:直接在绘图时计算总数值,适配你原有写法)

ggplot(dealflow_summary_fiscal_yr, aes(x = Total, y = Type, fill = status)) +
  geom_bar(stat = "identity", width = 0.6) +
  # 分段内部计数标注
  geom_text(aes(label = Total),
            position = position_stack(vjust = 0.5),
            color = "white",
            size = 3) +
  # 总数值标注(调整原有stat_text的对齐参数)
  geom_text(aes(label = stat(x), group = Type),
            stat = "summary", fun = sum,
            hjust = -0.2,
            vjust = 0.5,
            color = "black",
            size = 3.5) +
  # 原有主题与样式设置
  theme_classic() +
  theme(
    axis.line.y = element_blank(),
    axis.ticks = element_blank(),
    legend.position = "bottom",
    axis.text.x = element_text(face = "bold", color = "black", size = 10, angle = 45, hjust = 1)
  ) +
  labs(x = "", y = "", fill = "") +
  scale_fill_manual(values = c("#284a8d", "#00B5CE")) +
  scale_x_continuous(expand = expansion(mult = c(0, 0.1)))

关键参数说明

  • position_stack(vjust = 0.5):自动将文字定位到每个堆叠分段的垂直中心位置,无需手动计算坐标
  • hjust = -0.2:将总数值文字锚定在堆叠条形末端的右侧,避免压在填充块上
  • scale_x_continuous(expand = expansion(mult = c(0, 0.1))):给x轴右侧留出10%的空白区域,防止总数值超出画布被截断
  • 分段标注用白色字体,可适配深色填充块的可读性需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.03 06:54:06