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

如何在ggplot堆叠条形图Y轴添加样本总数(n值)?

ggplot堆叠条形图Y轴添加样本总数的实现方法

不需要手动逐个添加标签,可通过数据预处理自动生成带样本计数的轴标签,具体步骤如下:

方法一:直接在数据流程中生成标签

在过滤数据后,通过分组统计样本量,合并物种名与计数为新的标签变量,再用于ggplot的y轴映射:

sur %>% 
  filter(!(species %in% c("Monkey", "Livestock (cattle/goat/sheep/pig/horse)"))) %>%
  # 按物种类别分组,统计每组样本数
  group_by(species_broad) %>%
  mutate(n = n()) %>%
  ungroup() %>%
  # 生成带样本计数的轴标签
  mutate(species_label = paste0(species_broad, " (n=", n, ")")) %>%
  ggplot(mapping=aes(y= species_label, fill=circumstances_bite_broad_intended)) + 
  geom_bar(colour="black" , position = "fill")+ 
  scale_x_continuous (labels=c("0","25%","50%","75%","100%"))  + 
  labs (x="Proportion of responses",y="Pet animal species")+ 
  ggtitle ("Circumstances of bite")+ 
  scale_fill_manual( values =c ("Threatening Engagement" = "darkred" ,
                                "Friendly Engagement" = "red" , 
                                "Practical Engagement" = "#EC7979" ,
                                "Unintentional Human Engagement" = "lightblue" ,
                                "Apparently unprovoked" = "darkblue"))

方法二:先统计计数表再合并(适合大数据量)

先单独统计每个物种的样本数,再合并到原数据中生成标签,避免重复计算:

# 第一步:统计各物种样本数
species_counts <- sur %>% 
  filter(!(species %in% c("Monkey", "Livestock (cattle/goat/sheep/pig/horse)"))) %>%
  count(species_broad, name = "n")

# 第二步:合并计数并生成标签
sur_processed <- sur %>% 
  filter(!(species %in% c("Monkey", "Livestock (cattle/goat/sheep/pig/horse)"))) %>%
  left_join(species_counts, by = "species_broad") %>%
  mutate(species_label = paste0(species_broad, " (n=", n, ")"))

# 第三步:绘图
ggplot(sur_processed, mapping=aes(y= species_label, fill=circumstances_bite_broad_intended)) + 
  geom_bar(colour="black" , position = "fill")+ 
  scale_x_continuous (labels=c("0","25%","50%","75%","100%"))  + 
  labs (x="Proportion of responses",y="Pet animal species")+ 
  ggtitle ("Circumstances of bite")+ 
  scale_fill_manual( values =c ("Threatening Engagement" = "darkred" ,
                                "Friendly Engagement" = "red" , 
                                "Practical Engagement" = "#EC7979" ,
                                "Unintentional Human Engagement" = "lightblue" ,
                                "Apparently unprovoked" = "darkblue"))

原理说明

通过dplyr的分组统计功能自动获取每个物种的样本量,将物种名称与(n=计数)格式的字符串合并为新变量,用该变量作为y轴的映射字段,即可让Y轴自动显示带样本数的类别标签,无需手动输入,且数据更新时标签会同步更新。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 07:38:19