如何用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代表患病。
| ID | Condition | Gender | Age | 年龄组 |
|---|---|---|---|---|
| 1 | 1 | M | 32 | 26-35岁 |
| 2 | 4 | F | 63 | 56-65岁 |
| 3 | 7 | M | 43 | 36-45岁 |
| 4 | 1 | F | 32 | 26-35岁 |
| 5 | 3 | F | 65 | 56-65岁 |
| 6 | 2 | M | 80 | 76-80岁 |
内容的提问来源于stack exchange,提问作者Usman YousafZai
相关产品推荐
相关产品推荐

