Search code examples
rggplot2nls

Plotting with ggplot2 a non linear regression obtained with NLS


I am trying to interpolate with ggplot2 an interpolated function and overlap it to the dotplot graph of the single values.

I obtain an error that I am not able to understand, like if I were binding two different vectors of different length.

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

The complete code is written below:

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)

I really do not understand where the mistake could be.

Thank you in advance for every reply!


Solution

  • I got it to run without errors by moving the formula argument. However the fit doesn't look particularly good though.

    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)
    

    Created on 2021-04-14 by the reprex package (v1.0.0)