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

如何在ggplot2分组柱状图中添加带正负号的百分比差值标签

分组柱状图添加百分比差值标签的实现方法

核心思路

先提前计算每个fuel_type分组下,no_car_21相对no_car_18的百分比差值,再将这些差值标签精准定位到对应柱子的上方。

完整代码示例

library(scales)
library(ggplot2)
library(dplyr)
library(tidyr)

# 1. 计算百分比差值(示例数据,替换为你的实际数据即可)
# 假设原始df结构:fuel_type | no_car_18 | no_car_21
df <- tibble(
  fuel_type = c("汽油", "柴油", "电动"),
  no_car_18 = c(12000, 8000, 3000),
  no_car_21 = c(15000, 7200, 6000)
)

# 生成标签数据框,计算并格式化差值
label_df <- df %>%
  mutate(
    diff_pct = ((no_car_21 - no_car_18)/no_car_18)*100,
    label = sprintf("%+.1f%%", diff_pct) # 强制显示正负号,保留1位小数
  )

# 2. 绘图并添加标签
df %>% 
  pivot_longer(-fuel_type) %>%
  ggplot(aes(x = fuel_type, y = value, fill = name)) +
  geom_col(position = position_dodge(width = 0.9)) +
  # 差值标签定位到no_car_21柱子上方
  geom_text(
    data = label_df,
    aes(x = fuel_type, y = no_car_21, label = label),
    position = position_dodge(width = 0.9), # 和柱子的偏移宽度保持一致
    vjust = -0.5, # 向上调整标签位置,避免和柱子重叠
    size = 4
  ) +
  scale_fill_manual(values = c("red", "blue")) +
  scale_y_continuous(
    labels = label_comma(),
    limits = c(0, max(df$no_car_21)*1.1) # 扩展y轴顶部,防止标签被截断
  ) +
  theme_bw()

关键细节说明

  • 修正了原代码的拼写错误:fuel_typ改为fuel_type,scale_y_continous改为scale_y_continuous
  • sprintf("%+.1f%%", diff_pct):%+强制显示正负号,.1f控制小数位数,%%输出百分号
  • position_dodge(width = 0.9):确保标签和对应分组的柱子完全对齐
  • 扩展y轴范围:避免标签超出绘图区域,保证显示完整

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 16:10:30