使用 ggplot2 绘制使用 NLS 获得的非线性回归

Plotting with ggplot2 a non linear regression obtained with NLS

我正在尝试使用 ggplot2 对插值函数进行插值,并将其与单个值的点图重叠。

我收到一个我无法理解的错误,就像我绑定两个不同长度的不同向量一样。

3: Computation failed in `stat_smooth()`:
arguments imply differing number of rows: 80, 6

完整代码写在下面:

library(ggplot2)

tabella <- data.frame("Tempo" = c(0, 15, 30, 60, 90, 120), "Visc" = c(500, 9125, 11250, 10875, 11325, 10375))
attach(tabella)

Visc.mod <- nls((Visc ~ 500 + (k1*Tempo/(k2+Tempo))), start=list(k1=100, k2=100), trace=TRUE)
cor(Visc,predict(Visc.mod))
predict(Visc.mod)
summary(Visc.mod)



ggplot(tabella, aes(x=Tempo, y=Visc)) + 
  geom_point() + 
  stat_smooth(method = "nls", 
              method.args = list(formula = "Visc ~ 500 + (k1*Tempo/(k2+Tempo))",
              start = list(k1=100, k2=100)), data = tabella, se = FALSE)

我真的不明白错误在哪里。

预先感谢您的每一个回复!

通过移动公式参数,我没有错误地得到了 运行。不过合身度不是特别好。

library(ggplot2)

tabella <- data.frame("Tempo" = c(0, 15, 30, 60, 90, 120), "Visc" = c(500, 9125, 11250, 10875, 11325, 10375))

ggplot(tabella, aes(x=Tempo, y=Visc)) + 
  geom_point() + 
  stat_smooth(method = "nls", formula = y ~ 500 + (k1 * x / (k2 + x)),
              method.args = list(start = list(k1=100, k2=100)), data = tabella, se = FALSE)

reprex package (v1.0.0)

于 2021-04-14 创建

代码的一个问题是公式是 nls 的参数,您需要将公式对象而不是字符传递给它。 其次,ggplot2 将 yx 传递给 nls 而不是 ViscTempo

ggplot(tabella, aes(x = Tempo, y = Visc)) +
geom_point()+
geom_smooth(
method = "nls",
formula = y ~ 500 + (k1 * x / (k2 + x)),
method.args = list(start = c(k1 = 100, k2 = 100)),
se=FALSE)
 

当@teunbrand 先于我时,我正在输入我的答案。但是,我使用 geom_smooth 而不是 stat_smooth 来放置它 同样的结果。不太合适