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

如何用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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 17:13:14