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

如何在ggplot箱线图中按fill字段分离额外数据集的点

解决geom_point未按type字段分离的问题

你的问题出在箱线图会自动按fill=type分组并错开排列,但散点图默认是重叠放置,导致sum_echt的红色点堆在一起。只需要给geom_point加上位置调整参数,让它和箱线图的分组对齐即可:

修改后的代码

ggplot() + 
  geom_boxplot(data = random_soort2, aes(x=categorie, y=fractie, fill=type), 
               position = position_dodge(width = 0.75)) +  # 显式设置箱线图的错开宽度
  theme_classic() +
  scale_fill_grey() +
  geom_point(data = sum_echt, aes(x=categorie, y = mean, group=type),  # 用group=type确保按类型分组
             colour="red", 
             position = position_dodge(width = 0.75))  # 和箱线图用相同的错开宽度

关键说明

  • 给geom_boxplot指定position_dodge(width = 0.75):固定箱线图分组的错开距离,方便散点图对齐
  • 给geom_point添加group=type:明确告诉ggplot要按type字段分组
  • 散点图的position_dodge宽度和箱线图保持一致:这样每个categorie下的不同type的点会和对应的箱线图一一对应,不会重叠

如果想让点的填充色也对应type(比如红色边框+对应填充色),可以把colour="red"改成shape=21,然后用fill=type:

ggplot() + 
  geom_boxplot(data = random_soort2, aes(x=categorie, y=fractie, fill=type), 
               position = position_dodge(width = 0.75)) +
  theme_classic() +
  scale_fill_grey() +
  geom_point(data = sum_echt, aes(x=categorie, y = mean, fill=type), 
             shape=21, colour="red",  # shape=21是带边框的实心点,fill控制填充色,colour控制边框
             position = position_dodge(width = 0.75))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 10:12:04