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

如何在geom_bar的Y轴添加多变量?以种族、性别分组为例

解决方案

问题背景

已有R代码生成按育儿活动分面的柱状图,展示各种族参与各类育儿活动的百分比。需求是在每个种族类别下方添加性别(sex变量)的参与百分比,且不生成“种族-性别”合并变量。

修改后完整代码

library(tidyverse)

dtest %>%
  filter(race2 != "Other NH") %>% 
  pivot_longer(cols = starts_with("ccare_"), 
               names_to = "ccare_variable", 
               values_to = "response") %>%
  # 新增sex到分组变量,计算每个活动、种族、性别的加权百分比
  group_by(ccare_variable, race2, sex) %>%
  summarise(percent_yes = weighted.mean(response == 1, useweight, na.rm = TRUE) * 100, .groups = "drop") %>%
  
  ggplot(aes(x = reorder(race2, percent_yes), y = percent_yes, fill = sex)) +
  # 使用position_dodge让同种族的性别柱子并排展示
  geom_bar(stat = "identity", 
           color = "black", 
           alpha = 0.7,
           position = position_dodge(width = 0.8)) +
  coord_flip() +
  labs(x = NULL, 
       y = "Percent",
       fill = "性别") +
  scale_x_discrete(labels = levels(dtest$race2)) +
  scale_fill_brewer(palette = "Set1") +
  facet_wrap(~ ccare_variable, scales = "free_y") +  
  theme_minimal(base_size = 15) +
  theme(panel.grid = element_blank(),
        legend.position = "bottom")

关键修改说明

  • 数据处理层:在group_by中加入sex变量,直接计算每个育儿活动、种族、性别的加权参与百分比,无需额外创建合并变量。
  • 绘图层:
    • 将fill映射从race2改为sex,用颜色区分性别分组。
    • 添加position = position_dodge(width = 0.8),让同一种族下的两个性别柱子并排显示,实现“种族类别下方展示性别百分比”的视觉效果。
    • 调整图例标题为“性别”,提升图表可读性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 23:44:52