当我使用geom_smooth nls拟合我的数据时,我得到了一个非常好的拟合。但是,如果我使用独立的nls函数来拟合我的数据,使用相同的方程和起始值,我得到的拟合要差得多。我想提取拟合参数,所以真的需要独立的nls来生成与geom_smooth nls相同的拟合。
对可能发生的事情有什么建议/提示吗?
df <- data.frame("x" = c(4.63794469, 1.54525711, 0.51508570, 0.17169523, 0.05737664, 5.11623138, 1.70461130, 0.56820377, 0.18940126, 0.06329358, 0.02109786),
"y" = c(0.1460101, 0.7081954, 0.9619413, 1.0192286, 1.0188301, 0.3114495, 0.7602488, 0.8205661, 0.9741323, 1.0922553, 1.1130464))
fit <- nls(data = df, y ~ (1/(1 + exp(-b*x + c))), start = list(b=1, c=0))
df$stand_alone_fit <- predict(fit, df)
df %>% ggplot() +
geom_point(aes(x = x, y = y)) +
scale_x_log10() +
ylim(0,1.2) +
geom_smooth(aes(x = x, y = y), method = "nls", se = FALSE,
method.args = list(formula = y ~ (1/(1 + exp(-b*x + c))), start = list(b= 1, c=0))) +
geom_line(aes(x = x, y = stand_alone_fit), color = "red") +
labs(title = "Blue: geom_smooth nls fit\nRed: stand alone nls fit")

发布于 2021-02-01 11:56:25
这里有两个问题,首先,预测(红线)仅在x点处执行,导致曲线看起来四四方方而不平滑。
第二,也是提出问题的原因。两条拟合曲线不相等是因为由于这条线scale_x_log10()在x轴上有变换,所以geom_smooth中的nls函数执行的拟合与独立拟合不同。
看看删除x轴变换后会发生什么。(绿线是来自外部拟合的更精细的预测)。
df <- data.frame("x" = c(4.63794469, 1.54525711, 0.51508570, 0.17169523, 0.05737664, 5.11623138, 1.70461130, 0.56820377, 0.18940126, 0.06329358, 0.02109786),
"y" = c(0.1460101, 0.7081954, 0.9619413, 1.0192286, 1.0188301, 0.3114495, 0.7602488, 0.8205661, 0.9741323, 1.0922553, 1.1130464))
fit <- nls(data = df, y ~ (1/(1 + exp(-b*x + c))), start = list(b=0, c=0))
df$stand_alone_fit <- predict(fit, df)
#finer resolution (green line)
new <- data.frame(x=seq(0.02, 5.1, 0.1))
new$y <-predict(fit, new)
df %>% ggplot() +
geom_point(aes(x = x, y = y)) +
# scale_x_log10() +
ylim(0,1.2) +
geom_smooth(aes(x = x, y = y), method = "nls", se = FALSE,
method.args = list(formula = y ~ (1/(1 + exp(-b*x + c))), start = list(b=0, c=0))) +
geom_line(aes(x = x, y = stand_alone_fit), color = "red") +
geom_line(data=new, aes(x, y), color="green") +
labs(title = "Blue: geom_smooth nls fit\nRed: stand alone nls fit")

或者在原始的ggplot定义中使用以下代码:method.args = list(formula = y ~ (1/(1 + exp(-b*10^(x) + 2*c))), start = list(b=-1, c=-3)))
https://stackoverflow.com/questions/65986592
复制相似问题