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

如何让geom_smooth()识别lm()模型结果中的公式?

用已有lm模型的公式给geom_smooth()指定拟合规则

其实这个需求很好实现,核心是把你已经拟合好的lm模型里的公式正确提取并转换成geom_smooth能识别的格式就行,不用每次都手动重复写公式,特别适合封装成函数的场景。

步骤拆解

  1. 提取模型中的公式
    你已经知道用fit$terms能查看公式,但它返回的是terms类型的对象,geom_smooth的formula参数需要的是标准的formula类型。所以我们用formula()函数把它转一下:
model_formula <- formula(fit)

这样得到的model_formula就是loss ~ hardness + strength这个标准公式对象了。

  1. 在geom_smooth中引用这个公式
    直接把提取到的公式传给geom_smooth()的formula参数就行,示例代码:
library(ggplot2)

ggplot(rubber, aes(x = hardness, y = loss)) +
  geom_point() +
  # 用模型里的公式做线性拟合
  geom_smooth(method = "lm", formula = model_formula)

这样绘图的时候就会自动用你之前lm模型的loss ~ hardness + strength公式来拟合,不用手动写啦。

封装成可复用函数

如果要封装成函数,让它更通用,比如支持指定x轴变量、自动适配不同的模型和数据,可以这么写:

plot_model_smooth <- function(fit_model, plot_data, x_col, y_col) {
  # 提取模型公式
  fit_formula <- formula(fit_model)
  
  ggplot(plot_data, aes(x = .data[[x_col]], y = .data[[y_col]])) +
    geom_point(color = "#2c3e50") +
    geom_smooth(
      method = "lm",
      formula = fit_formula,
      color = "#e74c3c",
      fill = "#f8d7da"
    ) +
    labs(title = paste("拟合线:", deparse(fit_formula)))
}

调用的时候就很灵活了:

# 用你之前的fit模型,画hardness和loss的关系
plot_model_smooth(fit, rubber, x_col = "hardness", y_col = "loss")

# 也可以换x轴为strength
plot_model_smooth(fit, rubber, x_col = "strength", y_col = "loss")

这里用.data[[x_col]]是为了避免ggplot的非标准求值问题,让函数更健壮。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:57:51