在R中绘制斜率固定为1的最佳拟合线性回归图
固定斜率为1的线性回归绘图方案(适配ggplot2分面)
问题背景
当前使用Windows 11 + R 4.4.3,基于ggplot2绘制工具A与工具B测量值的回归图,核心需求如下:
- 强制回归斜率为1,仅求解截距b(方程形式:
y = b + 1*x) - 支持
facet_wrap/facet_grid实现多面板批量绘制 - 保留散点展示、y=x参考线、回归方程标注等核心元素
数据集代码:
df <- data.frame( A= c(1.313, 1.3118, 1.3132, 1.3122, 1.3128, 1.3061, 1.3051, 1.3052, 1.3069, 1.3053, 1.3072, 1.3006, 1.3246, 1.3229, 1.3254, 1.3239, 1.3222, 1.3155, 1.313, 1.3147, 1.3174, 1.3174, 1.3188, 1.3134), B=c(1.3165, 1.316, 1.3176, 1.316, 1.3169, 1.3104, 1.3094, 1.3095, 1.3107, 1.3101, 1.3112, 1.3047, 1.3285, 1.3271, 1.3297, 1.3274, 1.3261, 1.3192, 1.318, 1.319, 1.322, 1.3215, 1.3232, 1.3172) )
核心解决方案
方案一:原生ggplot2+ggpubr适配(简洁版)
利用lm中的offset()函数强制x的系数为1,直接在geom_smooth和stat_regline_equation中指定约束模型,原生支持分面逻辑。
代码示例:
library(ggplot2) library(ggpubr) # 单面板绘图 ggplot(df, aes(x = A, y = B)) + geom_point(size = 2) + geom_abline(slope = 1, intercept = 0, linetype = "dashed", color = "gray50") + # 固定斜率为1的回归:offset(x)强制x系数为1,仅拟合截距b geom_smooth( color = "red", method = "lm", se = FALSE, formula = y ~ 1 + offset(x) ) + # 匹配约束模型公式,让stat_regline_equation正确计算并标注 stat_regline_equation( label.x = 1.31, label.y = 1.325, formula = y ~ 1 + offset(x), aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~")) ) + coord_equal() # 多面板示例(先给数据集添加分组列) df_grouped <- df %>% mutate(group = rep(c("Group1", "Group2"), each = 12)) ggplot(df_grouped, aes(x = A, y = B)) + geom_point(size = 2) + geom_abline(slope = 1, intercept = 0, linetype = "dashed", color = "gray50") + geom_smooth( color = "red", method = "lm", se = FALSE, formula = y ~ 1 + offset(x) ) + stat_regline_equation( label.x = 1.31, label.y = 1.325, formula = y ~ 1 + offset(x), aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~")) ) + facet_wrap(~group) + coord_equal()
方案二:预计算参数+自定义标注(灵活版)
先按分组批量计算截距b和R²,再用geom_abline绘制回归线、geom_text标注方程,适合需要对回归结果做额外处理的场景。
代码示例:
library(dplyr) library(ggplot2) # 按分组计算回归参数 fit_results <- df_grouped %>% group_by(group) %>% summarise( b = coef(lm(B ~ 1 + offset(A)))[[1]], r_squared = summary(lm(B ~ 1 + offset(A)))$r.squared, .groups = "drop" ) %>% mutate( eq_label = paste0("y = ", round(b, 4), " + 1*x"), r_label = paste0("R² = ", round(r_squared, 4)), full_label = paste(eq_label, r_label, sep = "\n") ) # 多面板绘图 ggplot(df_grouped, aes(x = A, y = B)) + geom_point(size = 2) + geom_abline(slope = 1, intercept = 0, linetype = "dashed", color = "gray50") + # 绘制固定斜率的回归线 geom_abline( data = fit_results, aes(intercept = b, slope = 1), color = "red", linewidth = 1 ) + # 标注回归方程与R² geom_text( data = fit_results, aes(x = 1.31, y = 1.325, label = full_label), hjust = 0, vjust = 1, size = 4 ) + facet_wrap(~group) + coord_equal()
关键说明
offset(x)是R中强制变量系数为1的标准写法,y ~ 1 + offset(x)完全等价于需求中的y = b + 1*x- 两种方案都原生支持
facet_wrap/facet_grid,分面时会自动按面板独立计算回归参数 - 方案一更简洁,直接复用ggplot2生态工具;方案二更灵活,便于对回归结果做二次分析或定制化展示
内容的提问来源于stack exchange,提问作者jeffgoblue
相关产品推荐
相关产品推荐

