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

如何用ggplot2的geom_bar展示各年龄组男女健康/患病占比

需求说明

希望在同一柱状图(geom_bar)中展示不同**年龄组(AgeGroup)里性别(Gender)对应的患病(sick)和健康(normal)**人群占比。以现有图表为例,18-25岁年龄组共有77949人,需在该组对应柱状内进一步呈现男女中健康与患病的百分比。

当前实现代码

library(tidyverse)
ggplot(data = people, aes(x = AgeGroup)) + 
  geom_bar(aes(fill = sex)) +
  geom_text(data = . %>% group_by(sex, AgeGroup) %>% 
              summarize(n = n()) %>% group_by(AgeGroup) %>%
              summarize(sex = sex, n = n, perc = n / sum(n)),
              aes(y = n, label = paste(scales::comma(n), 
                                       scales::percent(perc, 0.1), 
                                       sep = '\n'), group = Gender), 
            position = position_stack(vjust = 0.5)) +
  geom_text(stat = "count", aes(label = scales::comma(after_stat(count))),
            nudge_y = 10000, fontface = 2) +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 90, hjust = 0),
        axis.text.y.left = element_blank(),
        axis.title.y.left = element_blank()) 

当前效果图

当前效果图

目标效果图(全年龄组示例)

目标效果图

测试数据框(Dummy Data Frame)

注:Condition=1代表健康,Condition>1代表患病。

IDConditionGenderAge年龄组
11M3226-35岁
24F6356-65岁
37M4336-45岁
41F3226-35岁
53F6556-65岁
62M8076-80岁

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 17:39:24