0

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!

GiacomoDB
  • 369
  • 1
  • 10

2 Answers2

2

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)

teunbrand
  • 33,645
  • 4
  • 37
  • 63
1

One issue with your code is that the formula is a parameter of nls and you need to pass a formula object to it and not a character. Secondly, ggplot2 passes y and x to nls and not Visc and Tempo

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)
 

I was typing my answer when @teunbrand preceded me. However, I place it using geom_smooth instead of stat_smooth Same result. Not a good fitenter image description here

Elia
  • 2,210
  • 1
  • 6
  • 18
  • Thank you both for your answer. I understoofd the mistake. The fit is not good because i put two random values as starting values. Changing them with more accuracy the result is much better. `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=12000, k2=2.5)), data = tabella, se = FALSE)` – GiacomoDB Apr 14 '21 at 11:44