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

使用ggrepel与ggplot2绘制带右侧标签的堆叠柱状图遇问题求助

堆叠柱状图标签对齐与颜色匹配解决方案

核心问题分析

  • 标签混乱/不对齐:未正确计算每个堆叠分段的中心位置,geom_text_repel默认位置易偏离分段
  • 颜色不匹配:标签颜色未与对应收入来源的填充色绑定

分步解决代码

1. 预处理数据:计算每个分段的中心坐标

先对数据按年份、收入来源排序,计算累计值的中点(即标签定位核心):

library(dplyr)
library(ggplot2)
library(ggrepel)

# 假设数据框名为df,包含year(年份)、source(收入来源)、value(收入)
df <- df %>%
  arrange(year, source) %>%
  group_by(year) %>%
  mutate(
    cumulative = cumsum(value),
    label_pos = cumulative - value/2  # 计算分段垂直中心
  ) %>%
  ungroup()

2. 绘制带精准标签的堆叠柱状图

绑定填充色与标签色,用计算好的label_pos固定标签位置:

ggplot(df, aes(x = factor(year), y = value, fill = source)) +
  geom_col() +
  geom_text(aes(y = label_pos, label = paste0("$", value), color = source),
            size = 3.5, show.legend = FALSE) +
  # 强制标签色与填充色一致
  scale_color_manual(values = scale_fill_manual()$palette) +
  labs(x = "年份", y = "收入", title = "公司各年份收入来源分布") +
  theme_minimal()

3. 可选:优化geom_text_repel的使用(避免标签重叠)

若需保留repel功能,限制其在分段范围内移动:

ggplot(df, aes(x = factor(year), y = value, fill = source)) +
  geom_col() +
  geom_text_repel(
    aes(y = label_pos, label = paste0("$", value), color = source),
    size = 3.5,
    show.legend = FALSE,
    # 限制标签在当前分段的上下边界内调整
    ylim = function(y) c(y - df$value[match(y, df$label_pos)]/2, 
                         y + df$value[match(y, df$label_pos)]/2),
    direction = "y"  # 仅允许垂直方向调整
  ) +
  scale_color_manual(values = scale_fill_manual()$palette) +
  labs(x = "年份", y = "收入", title = "公司各年份收入来源分布") +
  theme_minimal()

关键注意事项

  • 必须确保数据按year和source排序,否则累计值计算会出错
  • label_pos是定位核心:用累计值减去当前分段的一半,精准锚定到分段中心
  • 通过scale_color_manual绑定填充色与标签色,彻底解决颜色不匹配问题

内容的提问来源于stack exchange,提问作者Edwin Acuña

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 13:07:04