You need to enable JavaScript to run this app. 如何修改ggplot分组百分比柱状图的顶部文本标签样式?
优惠活动
大模型
产品
解决方案
定价
更多

如何修改ggplot分组百分比柱状图的顶部文本标签样式?

修正后完整可运行代码

library(ggplot2)
# 示例数据集
df <- structure(list(year = c("2018", "2018", "2018", "2018", "2018", 
"2018", "2018", "2018", "2018", "2018", "2018", "2018", "2018", 
"2018", "2018", "2018", "2018", "2018", "2018", "2018", "2018", 
"2018", "2018", "2018", "2018", "2018", "2018", "2018", "2018", 
"2018"), hours.48 = c("Yes", "No", "No", "No", "Yes", "No", "No", 
"No", "No", "No", "No", "No", "No", "No", "Yes", "No", "No", 
"No", "No", "No", "No", "No", "No", "No", "No", "No", "No", "No", 
"No", "No")), row.names = c(NA, 30L), class = "data.frame")

ggplot(df, aes(x = hours.48, fill = hours.48)) +
  geom_bar(aes(y = (..count..)/sum(..count..) * 100), width = 0.7) + 
  labs(x = "工作时长≥48小时", y = "员工占比%", fill = "工作时长≥48小时", title = "法规生效后") + 
  theme_minimal() +
  scale_fill_manual(values = c("orange", "blue")) + 
  geom_text(aes(label = paste0(round((..count..)/sum(..count..) * 100, 1), "%"), 
                y = (..count..)/sum(..count..) * 100), 
            stat= "count", vjust = -0.2, color = "white", size = 3.5) +
  theme(legend.position = "top")

修改说明

  • 文本白色:在geom_text参数中添加color = "white"直接设定文本颜色
  • 保留1位小数:用round()函数对计算得到的百分比值保留1位小数,拼接%符号符合百分比展示逻辑
  • 位置对齐:将geom_text的y坐标和geom_bar的y坐标统一为相同的百分比计算逻辑,替换原有错误的..prop..参数,配合vjust = -0.2微调文本与柱子顶部的间距

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 11:27:01