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

使用ggplot2绘制带回归线的箱线图:解决回归线偏移问题

箱线图叠加回归线显示异常的解决方法

尝试创建带有回归线的箱线图时,出现图形无法重叠、回归线位置过于靠右的显示异常问题。

原代码

library(ggplot2)

ggplot(Dados_geom_smooth[!is.na(Dados_geom_smooth$Day),]) +
  geom_boxplot(aes(x=factor(Day), y = absolute_CD45posi, fill = Grupos_gravidade),
               position=position_dodge(.7),width=.8)+
  geom_smooth(aes(x=as.integer(Day),
                  y=absolute_CD45posi, color=Grupos_gravidade,
                  fill=Grupos_gravidade),method=loess) + 
  facet_wrap(~ Grupos_gravidade) + 
  theme_bw()

dev.copy(tiff,"absolute_CD45posi.tiff",width=4, height=3, units="in",res=300)
dev.off()

解决方案

修改geom_smooth的x轴映射逻辑,并添加x轴离散刻度限制,修正后的关键代码如下:

geom_smooth(aes(x=as.numeric(as.factor(Day)),
                y=absolute_CD45posi, color=Grupos_gravidade,
                fill=Grupos_gravidade),method=loess) +  
scale_x_discrete(limits = c("2","5", "10"))

修正说明

原代码中直接使用as.integer(Day)转换x轴变量,会导致箱线图(x轴为因子类型)和回归线(x轴为原始整数)的坐标映射不匹配,进而出现位置偏移。改用as.numeric(as.factor(Day))可以将因子类型的Day转换为对应顺序的数值,和箱线图的x轴坐标对齐;同时通过scale_x_discrete指定x轴刻度范围,确保两类图形元素正确重叠显示。

内容的提问来源于Stack Exchange,提问作者Giuseppe Gianini

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 18:10:49