如何强制ggplot2中的回归直线从(0,100)点起始?
强制回归直线过(0,100)并显示对应约束方程
问题说明
当前用ggplot绘制的回归直线未从(0,100)点起始,需要达成两个目标:
- 让回归直线强制经过(0,100)
- 显示的直线方程要体现“截距固定为100”的约束
你当前使用的代码:
ggplot(DTT_Half, aes(x = Time.in.minutes, y = Percentage.of.DTT)) + geom_point() + coord_cartesian(ylim = c(0,105), xlim = c(0, 10.5)) + stat_smooth(method = "lm", se = FALSE) + scale_y_continuous(expand = c(0,0), breaks = seq(0, 100, by = 10))+ scale_x_continuous(expand = c(0,0)) + stat_regline_equation(label.y = 100, label.x = 7.5, aes(label = ..eq.label..))
当前效果:
解决方法
要强制直线过(0,100),本质是让线性模型的截距固定为100,只拟合斜率。下面提供两种实用实现方式:
方法1:直接在stat_smooth中指定约束公式
通过调整formula参数,把y值偏移100后做无截距回归,再配合修改方程显示文本:
# 需要先加载stringr包处理方程文本 library(stringr) ggplot(DTT_Half, aes(x = Time.in.minutes, y = Percentage.of.DTT)) + geom_point() + coord_cartesian(ylim = c(0,105), xlim = c(0, 10.5)) + # 核心:用I(y-100)~x-1强制模型过(0,100) stat_smooth(method = "lm", se = FALSE, formula = I(y - 100) ~ x - 1) + scale_y_continuous(expand = c(0,0), breaks = seq(0, 100, by = 10))+ scale_x_continuous(expand = c(0,0)) + # 调整方程显示,把默认的I(y-100)=kx改成y=100+kx stat_regline_equation(label.y = 100, label.x = 7.5, aes(label = paste0("y = 100 + ", str_remove(..eq.label.., "^I\\(y - 100\\) = "))))
方法2:手动拟合模型再绘制直线
这种方式更灵活,方程显示完全可控:
# 先拟合带约束的模型:固定截距为100,只计算斜率 lm_model <- lm(I(Percentage.of.DTT - 100) ~ Time.in.minutes - 1, data = DTT_Half) slope <- round(coef(lm_model)[[1]], 2) # 保留两位小数让方程更美观 # 生成直线的坐标数据 line_data <- data.frame( Time.in.minutes = seq(0, 10.5, 0.1), Percentage.of.DTT = 100 + slope * seq(0, 10.5, 0.1) ) # 绘图 ggplot(DTT_Half, aes(x = Time.in.minutes, y = Percentage.of.DTT)) + geom_point() + coord_cartesian(ylim = c(0,105), xlim = c(0, 10.5)) + geom_line(data = line_data, color = "#00BFC4") + # 绘制约束后的直线 scale_y_continuous(expand = c(0,0), breaks = seq(0, 100, by = 10))+ scale_x_continuous(expand = c(0,0)) + # 添加自定义方程文本 annotate("text", x = 7.5, y = 100, label = paste0("y = 100 + ", slope, "x"))
内容的提问来源于stack exchange,提问作者Ashvanth
相关产品推荐
相关产品推荐


