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

如何在R ggplot的百分比条形图中添加计数标签?

嘿,我来帮你搞定在ggplot百分比条形图上添加计数标签的事儿!首先我先把你没写完的数据补全(最后两个Count值我假设是50和40,方便演示),然后一步步来:

第一步:补全并准备数据

先把完整的数据框写出来,同时用dplyr计算每个区域的总人数、性别占比,还要准备好要显示的标签(可以是纯计数,也可以是计数+百分比,这里我做后者,更实用):

# 加载需要的包
library(dplyr)
library(ggplot2)

# 补全后的示例数据
MYDATA <- data.frame(
  Region = c(1, 1, 2, 2, 3, 3, 4, 4, 5, 5),
  Sex = c("M", "F", "M", "F", "M", "F", "M", "F", "M", "F"),
  Count = c(185, 130, 266, 201, 304, 283, 102, 60, 50, 40)
)

# 计算占比和标签
data_with_labels <- MYDATA %>%
  group_by(Region) %>%
  mutate(
    Total = sum(Count),
    Pct = round(Count / Total * 100, 1), # 保留1位小数的百分比
    Label = paste0(Count, " (", Pct, "%)") # 组合计数和百分比标签
  ) %>%
  ungroup()

第二步:绘制堆叠百分比条形图+标签

如果是堆叠式的占比条形图,用position_stack来让标签居中在每个条形块里:

ggplot(data_with_labels, aes(x = factor(Region), y = Pct, fill = Sex)) +
  geom_bar(stat = "identity", position = "stack") +
  # 添加标签,vjust=0.5让标签在条形块垂直居中
  geom_text(aes(label = Label), position = position_stack(vjust = 0.5), size = 3) +
  # 美化图表
  labs(
    x = "区域",
    y = "占比(%)",
    fill = "性别",
    title = "各区域性别分布(含计数与占比)"
  ) +
  theme_minimal()

第三步:分组式百分比条形图+标签

如果你想要的是每个区域下分两个条形分别显示男女占比,那就用position_dodge调整布局,同时把标签放在条形上方:

ggplot(data_with_labels, aes(x = factor(Region), y = Pct, fill = Sex)) +
  geom_bar(stat = "identity", position = position_dodge(width = 0.9)) +
  # 让标签和条形对齐,vjust=-0.5把标签放在条形上方
  geom_text(aes(label = Label), position = position_dodge(width = 0.9), vjust = -0.5, size = 3) +
  labs(
    x = "区域",
    y = "占比(%)",
    fill = "性别",
    title = "各区域性别占比(含计数与占比)"
  ) +
  theme_minimal() +
  # 调整y轴上限,避免标签超出图表范围
  ylim(0, max(data_with_labels$Pct) + 10)

小提示

如果只需要显示纯计数标签,不用百分比,直接把Label改成as.character(Count)就行,其他代码不用动~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:15:43