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

ggplot2分组箱线图:如何将散点匹配至对应子组箱线?

解决ggplot2分组箱线图散点对应问题

你的问题出在箱线图会按Ratio分组自动偏移位置,但散点层没有同步这个偏移逻辑,导致同一Time下的所有散点都堆在x轴的中心位置,没对应到各自的Ratio分组箱线。

修改方案

给geom_jitter添加position_dodge参数,让散点和对应分组的箱线对齐,同时规范填充色的设置避免顺序错误:

library(ggplot2)

# 数据准备代码
Ratio= c("1/1","1/1","1/1","1/1","1/5","1/5","1/5","1/5","1/10","1/10","1/10","1/10")
Exp=c(1,2,1,2,1,2,1,2,1,2,1,2)
Val=c(1,1,1,1,0.645,0.89,1.45,2.67,5.43,6.3,8.4,9.5)
Time=c(1,1,24,24,1,1,24,24,1,1,24,24)

df=data.frame(cbind(Time,Ratio,Val,Exp))
df[,c(1,3:4)] = apply(df[,c(1,3:4)], 2, function(x) as.numeric(as.character(x)))

# 修改后的绘图代码
ggplot(df, aes(x=factor(Time), y=Val, color=factor(Ratio), fill=factor(Ratio)))+
  theme(axis.line = element_line(colour = "black"),
        axis.text = element_text(family="Arial",colour="black",size=(13)),
        axis.title = element_text(family="Arial",colour="black",size=(15)),
        axis.title.y = element_text(margin=margin(t=0,r=0,b=5,l=1)),
        axis.ticks.x=element_blank(),
        panel.grid.major = element_blank(), 
        panel.grid.minor = element_blank(),
        panel.border = element_blank(),
        panel.background = element_blank())+
  geom_boxplot(width = 0.9, outlier.shape = NA, position = position_dodge(width = 0.9)) +
  ylim(0, 10) +
  # 关键:添加position_dodge让散点跟随分组偏移
  geom_jitter(color="black", width = .05, alpha = .8, position = position_dodge(width = 0.9)) +
  labs(y= "expression (fold change)", x = "Time") +
  # 明确对应Ratio与填充色,避免顺序错误
  scale_fill_manual(name = "ratio", values = c("1/1"="lightsalmon1", "1/5"="azure2", "1/10"="skyblue1")) +
  scale_color_discrete(name = "ratio")

关键修改点说明

  1. 统一分组偏移逻辑:给geom_boxplot和geom_jitter设置相同的position_dodge(width = 0.9),确保散点正好落在对应分组的箱线范围内,宽度值要和箱线图的width参数匹配。
  2. 规范填充色映射:将fill映射到Ratio字段,用scale_fill_manual明确每个分组对应的颜色,避免原手动赋值方式因数据顺序变化出错。
  3. 统一图例名称:通过scale_color_discrete将颜色图例名称设为"ratio",和填充图例保持一致,让图表更整洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 16:23:27