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

R语言ggplot2绘制条形图时如何获取正确分组占比(无需新增列)

问题根因

你现有代码中prop.table(stat(count))计算的是全数据集的整体占比,而非你需要的按国家分组后的组内占比,因此和手动计算的列占比结果不符。

方案1:无需新增数据集列(ggplot2原生实现,优先匹配你的需求)

通过after_stat()结合分组求和计算组内占比,不需要提前修改原数据集,修正后的代码如下:

library(ggplot2)
library(dplyr)

bigcats %>% 
  ggplot(aes(x = country, 
             fill = cat_type,
             y = after_stat(count / ave(count, group, FUN = sum)),
             label = after_stat(scales::percent(count / ave(count, group, FUN = sum))))) +
  geom_bar(position = position_fill()) + 
  geom_text(stat = "count", position = position_fill(vjust = 0.5), colour = "white", size = 5) +
  labs(y = "Percent", title = "Top Big Cat Populations", x = "Country") +
  scale_fill_discrete(name = NULL, labels = c("Siberian/Bengal", "Other wild cats", "Puma/Leopard/Jaguar")) +
  scale_y_continuous(labels = scales::percent)

逻辑说明:ave(count, group, FUN = sum)会按ggplot2默认的group分组(即x轴的country分组)计算每个国家的总样本数,单类别的count除以该值即可得到对应国家内的分类占比,和你手动计算的结果完全一致。

方案2:提前汇总新增列方案(可读性更高,可选)

如果不需要严格限制不修改数据集,提前计算占比的写法更直观易维护:

library(ggplot2)
library(dplyr)

# 先按分组统计占比
bigcats_stat <- bigcats %>%
  count(country, cat_type) %>%
  group_by(country) %>%
  mutate(pct = n / sum(n))

# 绘图
bigcats_stat %>%
  ggplot(aes(x = country, y = pct, fill = cat_type, label = scales::percent(pct))) +
  geom_col(position = position_fill()) +
  geom_text(position = position_fill(vjust = 0.5), colour = "white", size = 5) +
  labs(y = "Percent", title = "Top Big Cat Populations", x = "Country") +
  scale_fill_discrete(name = NULL, labels = c("Siberian/Bengal", "Other wild cats", "Puma/Leopard/Jaguar")) +
  scale_y_continuous(labels = scales::percent)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 22:45:02