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

如何在R语言的百分比堆叠柱状图内部添加数值标签

解决ggplot2百分比堆叠柱状图添加数量标签时Y轴异常的问题

问题出在geom_text使用的position_stack(0.5)是基于原始数值的堆叠定位,而你的柱状图用的是position = "fill"(按百分比缩放),两者坐标体系不匹配,导致Y轴被原始数量值覆盖。

要解决这个问题,只需要把geom_text的定位方式改成和柱状图一致的position_fill(vjust=0.5),这样标签会自动在百分比堆叠的区块居中显示,同时保持Y轴的百分比刻度。

修改后的完整代码如下:

library(ggplot2)
library(ggthemes)
library(scales)
library(dplyr)

Sweets <- c("Smarties", "Smarties", "Jelly beans", "Jelly beans", "Jelly tots", "Jelly tots", "Astros", "Astros")
Sweet_Colour <- c("Blue","Red", "Blue","Red", "Blue","Red","Blue","Red")
Colour_Quantity <- c(13,14,25,36,96,85,9,12)
df <- data.frame(Sweets, Sweet_Colour, Colour_Quantity)

pl <- ggplot(data = df, aes(x = Sweets, y= Colour_Quantity, fill = Sweet_Colour)) +
  geom_bar(stat="identity", position = "fill") +
  scale_y_continuous(labels = percent) +
  ggthemes::theme_tufte() +
  theme(axis.ticks.x= element_blank(),
        axis.text.x = element_text(angle = 90, hjust = 0),
        legend.position="top",
        text = element_text(size=20)) +
  labs(x = "Sweet Type", y= "Percentage of Blue and Red Sweets") +
  scale_fill_discrete(name = "") +
  # 关键修改:使用position_fill替代position_stack,保证和柱状图缩放逻辑一致
  geom_text(aes(label = Colour_Quantity), size = 3, position = position_fill(vjust = 0.5))

pl

核心逻辑说明:
position_fill(vjust=0.5)会让标签在每个百分比堆叠的区块垂直居中,完全匹配柱状图的百分比缩放逻辑,既保留了原始数量的标签显示,又不会干扰Y轴的百分比刻度展示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 05:15:33