类似于这里的帖子:如何使用`geom_smooth()`绘制多个`nls`拟合曲线(在函数调用中获取模型参数)
我想用 ggplot2 和自启动函数绘制 nls 的非线性回归输出。当方法设置为“drm”时,我可以轻松地做到这一点,但无法用“nls”正确地弄清楚。
这是我尝试过的:
我可以使用这些数据来拟合带有 drc 的模型并将其绘制如下:
df <- structure(list(iv = c(1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1,
2, 3, 4, 5, 6), dv = c(9.2, 8.5, 13.5, 15.8, 18.3, 17.7, 8.7,
10.8, 14.3, 15, 18, 15.3, 8.7, 14.6, 14.8, 16.8, 15.8, 15.8)), row.names = c(NA,
-18L), class = c("tbl_df", "tbl", "data.frame"))
drm_asymp <- drm(
dv ~ iv,
data = df,,
fct = AR.2(names = c("Asym", "lrc"))
)
> drm_asymp
A 'drc' model.
Call:
drm(formula = dv ~ iv, data = df, fct = AR.2(names = c("Asym", "lrc")))
Coefficients:
Asym:(Intercept) lrc:(Intercept)
17.22 1.62
> ggplot(data = df, aes(x = iv, y = dv)) +
geom_smooth(
method = drm,
se = F,
data = df,
method.args = list(fct = AR.2()),
)
但是如果我尝试与 nls 相同/相似,我会失败:
nls_asymp <- nls(
dv ~ SSasympOrig(iv, Asym, lrc),
data = df
)
> nls_asymp
Nonlinear regression model
model: dv ~ SSasympOrig(iv, Asym, lrc)
data: df
Asym lrc
17.2159 -0.4821
residual sum-of-squares: 37.46
Number of iterations to convergence: 0
Achieved convergence tolerance: 5.807e-07
尝试这些绘图方法中的任何一种都会产生空白图和错误:
ggplot(data = df, aes(x = iv, y = dv)) +
geom_smooth(
method = nls,
se = F,
data = df
)
`geom_smooth()` using formula = 'y ~ x'
Warning: Failed to fit group -1.
Caused by error in `attr(data, "parameters") %||% {
len <- length(object)
if (len == 1L) stop("argument 'object' has an impossible length")
LHS <- if (len == 3L) object[[2L]]
RHS <- object[[len]]
if (!is.call(RHS)) stop("right-hand side of formula is not a call")
func <- eval(RHS[[1L]], environment(object))
getInitial(func, data, mCall = as.list(match.call(func, call = RHS)), LHS = LHS, ...)
}`:
! right-hand side of formula is not a call
ggplot(data = df, aes(x = iv, y = dv)) +
geom_smooth(
method = nls,
se = F,
data = df,
method.args = list(formula = dv ~ SSasympOrig(iv, Asym, lrc)),
)
`geom_smooth()` using formula = 'y ~ x'
Warning: Failed to fit group -1.
Caused by error in `method()`:
! parameters without starting value in 'data': dv, iv, Asym, lrc
需要将公式中的iv和dv替换为x和y。 另外,由于某种原因,Asym 和 lrc 需要起始值。
ggplot(data = df, aes(x = iv, y = dv)) +
geom_point() +
geom_smooth(
method = nls,
se = F,
method.args = list(formula = y ~ SSasympOrig(x, Asym, lrc), start=list(Asym=17, lrc=-.5))
)