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

如何在R ggplot填充条形图对应分组内叠加geom_jitter散点

问题原因

代码的核心问题有两处:

  1. y轴映射不匹配:条形图的y轴是分组计数数值,但你给geom_jitter映射的y轴是分类变量ethnicity,二者坐标轴范围完全不一致,自然无法对齐。
  2. 未匹配分组偏移:按种族填充的条形有固定的分组位置,直接使用geom_jitter不会自动对齐到对应种族的填充区域。

修正代码

首先加载所需依赖包:

library(tidyverse)

完整修正后的绘图代码如下:

# 示例数据
df = tribble(
  ~id, ~agegroup, ~ethnicity,
  "a", "20s", "African Descent",
  "b", "30s", "White",
  "c", "50s", "White",
  "d", "40s", "Hispanic",
  "e", "20s", "White",
  "f", "30s", "Hispanic",
  "g", "20s", "Hispanic",
  "h", "30s", "White",
  "i", "20s", "African Descent",
  "j", "30s", "White",
  "k", "50s", "White",
  "l", "20s", "White",
  "m", "30s", "Hispanic",
  "n", "20s", "Hispanic",
  "o", "30s", "White",
)

# 数据预处理:按年龄组、种族分组,为组内每个个体生成y轴位置,确保落在对应填充块范围内
df <- df %>%
  group_by(agegroup, ethnicity) %>%
  mutate(y_pos = row_number()) %>%
  ungroup()

# 绘制堆叠条形图+对应分组散点
dmplot <- ggplot(df, aes(x = agegroup, fill = ethnicity)) +
  geom_bar(stat = "count") +
  labs(
    x = "Age Group",
    y = paste0("Population (total = ", nrow(df), ")")
  ) +
  geom_jitter(
    aes(y = y_pos, color = ethnicity),
    width = 0.2, # 控制左右抖动范围,避免跑出对应年龄组
    height = 0.3, # 控制上下抖动范围,避免跑出对应填充块
    alpha = 0.8,
    show.legend = FALSE # 避免和填充图例重复
  )

dmplot

可选适配方案

如果你需要的是并列分组条形图而非堆叠条形图,只需修改位置参数即可对齐:

dmplot <- ggplot(df, aes(x = agegroup, fill = ethnicity)) +
  geom_bar(stat = "count", position = position_dodge(width = 0.9)) +
  labs(
    x = "Age Group",
    y = paste0("Population (total = ", nrow(df), ")")
  ) +
  geom_jitter(
    aes(y = y_pos, color = ethnicity),
    position = position_jitterdodge(jitter.width = 0.1, jitter.height = 0.2, dodge.width = 0.9),
    alpha = 0.8,
    show.legend = FALSE
  )

dmplot

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 13:15:07