如何用R ggplot绘制自定义筛选子集的堆叠条形图?
自定义子集堆叠条形图实现方法
要实现每个条形对应自定义数据子集的堆叠对比,核心是先给每个子集添加专属分组标签,再合并数据集统一绘图,具体操作如下:
完整代码
library(ggplot2) library(dplyr) # 加载内置数据 data(starwars) # 创建带分组标签的自定义子集 naboo_group <- starwars %>% filter(homeworld == "Naboo") %>% mutate(custom_group = "纳布星球角色") tatooine_group <- starwars %>% filter(homeworld == "Tatooine") %>% mutate(custom_group = "塔图因星球角色") human_group <- starwars %>% filter(species == "Human") %>% mutate(custom_group = "人类角色") # 合并所有子集 merged_data <- bind_rows(naboo_group, tatooine_group, human_group) # 绘制百分比堆叠条形图 ggplot(merged_data, aes(x = custom_group, fill = gender)) + geom_bar(position = "fill") + labs(x = "自定义分组", y = "占比", fill = "性别") + theme(axis.text.x = element_text(angle = 45, hjust = 1))
关键逻辑说明
- 子集分组标记:用
mutate()给每个筛选出的子集添加唯一的分组名称,这是让ggplot识别不同条形的核心 - 数据合并:通过
bind_rows()把多个子集整合为一个数据集,避免多次绘图拼接的麻烦 - 绘图参数:保持
position = "fill"来生成百分比堆叠效果,方便直接对比不同子集的性别分布比例
内容的提问来源于stack exchange,提问作者Kaikus
相关产品推荐
相关产品推荐

