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

如何在ggplot的facet_wrap/facet_grid中添加百分比geom_text标签?

解决方案

首先需要按z分组计算每个y在对应组内的百分比,再将该百分比作为标签传入geom_text。以下是完整代码:

1. 加载依赖包并处理数据

library(ggplot2)
library(dplyr)

# 原始数据框
df = data.frame(x = rep(1:5, 3),
                z = rep(1:3, each = 5),
                y = 100:114 )

# 按z分组计算百分比,格式化为带1位小数的百分比字符串
df <- df %>%
  group_by(z) %>%
  mutate(percent = sprintf("%.1f%%", y / sum(y) * 100)) %>%
  ungroup()

2. 修改ggplot代码

ggplot(df) +
  aes(x = x, fill = x, y = y) +
  geom_col(position = 'dodge') +
  facet_wrap(~z) +
  geom_text(aes(label = percent),
            position = position_dodge(1),
            vjust = -1, hjust = 0.5, # 调整hjust让文字在柱子上方居中
            color = 'white') +
  theme_dark() +
  scale_fill_gradient(low = 'orange', high = 'red')

补充说明

  • 若不需要百分比的小数位,可将sprintf的格式改为"%.0f%%"
  • 也可以使用scales包的percent函数替代sprintf,写法为:percent(y/sum(y), accuracy = 0.1)
  • hjust参数可根据需求调整,原代码的hjust=0会让文字偏右,改为0.5实现居中效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 13:35:23