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

自定义nls插值geom_smooth失效:强制过原点问题排查

问题原因与解决方法

核心原因

  1. 自定义函数未处理权重参数:geom_smooth会把weight映射传递给指定的拟合方法,但你写的nls_se函数在调用底层nls()时,完全没传递权重参数。nls()本身支持通过weights参数设置权重,但你的代码里根本没用到这个参数,导致原点的高权重完全没生效。
  2. 模型公式的冗余设置:你用的公式y ~ (a * x) + b保留了截距项b,就算权重生效,也只是让模型尽量向原点靠拢,没法严格强制过原点——靠权重约束不如直接去掉截距项更可靠。

修复方案

1. 修改自定义nls_se函数,支持权重传递

nls_se <- function(formula, data, start, weights = NULL, ...) {
  # 把weights参数传递给nls()
  mod <- nls(formula, data = data, start = start, weights = weights, ...)
  class(mod) <- "nls_se"
  mod
}

predict.nls_se <- function(model, newdata, level = 0.9, ...) {
  class(model) <- "nls"
  p <- investr::predFit(model, newdata = newdata, 
                        interval = "confidence", level = level)
  list(fit = p, se.fit = p[,3] - p[,1])
}

2. 严格强制过原点:使用无截距模型(更可靠)

如果要确保拟合线必过(0,0),直接去掉公式里的截距项,不需要依赖权重:

Graph <- ggplot(data=RawData, aes(x=`a`, y=`b`, col=Grade)) + 
  geom_point(aes(color = Grade), shape = 1, size = 2.5) +
  # 无截距公式y ~ a*x,初始值只需要设置a
  geom_smooth(level=0.8, method = nls_se, 
              formula=y ~ a * x, method.args = list(start = list(a = 1))) +
  scale_color_manual(values=c('#f92410','#644196', '#33b90e'))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 02:10:35