how to use method="nlsLM" (in packages minpack.lm) in geom_smooth

1.1k Views Asked by At
test <- data.frame(Exp = c(4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 
5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6), t = c(0, 0.33, 0.67, 
1, 1.33, 1.67, 2, 4, 6, 8, 10, 0, 33, 0.67, 1, 1.33, 1.67, 2, 4, 6, 8, 10, 
0, 0.33, 0.67, 1, 1.33, 1.67, 2, 4, 6, 8, 10), fold = c(1, 
0.957066345654286, 1.24139015724819, 1.62889151698633, 1.72008539595879, 
1.82725412314402, 1.93164365299958, 1.9722929538061, 2.15842019312484, 
1.9200507796933, 1.95804730344453, 1, 0.836176542548747, 1.07077717914707, 
1.45471712491441, 1.61069357875771, 1.75576377806756, 1.89280913889538, 
2.00219054189937, 1.87795513639311, 1.85242493827193, 1.7409346372629, 1, 
0.840498729335292, 0.904130905000499, 1.23116185602517, 1.41897551928886, 
1.60167656534099, 1.72389226836308, 1.80635095956481, 1.76640786872057, 
1.74327897001172, 1.63581509884482))

d <- ggplot(test,aes(x=t, y=fold))+ 
     #to make it obvious I use argument names instead of positional matching
geom_point()+
geom_smooth(method="nls", 
          formula=y~1+Vmax*(1-exp(-x/tau)), # this is an nls argument
          method.args = list(start=c(tau=0.2,Vmax=2)), # this too
          se=FALSE)

I find the code here in this site, but I wonder how to change method="nls" to method = "nlsLM" in geom_smooth, as the original "nls" is really a big problem to me when setting the start values. Is there any ways to use packages from cran in the method of geom_smooth in ggplot2? Thanks

3

There are 3 best solutions below

1
On

It's probably best to keep your nls results in a separate data frame, and plot the two items separately:

ggplot() + 
    geom_point(aes(x=t, y=fold), data = test) + 
    geom_line(aes(...), data = my.nls.results)
5
On

You don't seem to have tried anything. You can simply do the obvious:

library(ggplot2)
library(minpack.lm)
d <- ggplot(test,aes(x=t, y=fold))+ 
  geom_point()+
  geom_smooth(method="nlsLM", 
              formula=y~1+Vmax*(1-exp(-x/tau)), 
              method.args = list(start=c(tau=0.2,Vmax=2)), 
              se=FALSE)
print(d)
#works

Note that convergence problems do not have an easy one-size-fits-all solution. Sometimes minpack can help, but often it will simply give you a bad fit where nls helpfully throws an error.

0
On

Use geom_line() instead.

For example, let's say you're working with mtcars and your formula is mpg ~ k / wt + b

nls_model <- nls(mpg ~ k / wt + b, data, etc.)

ggplot(...) +
geom_line(stat = "smooth",
          method = "nls",
          formula = y ~ k / x + b,
          method.args = list(start = as.list(coef(nls_model))),
          se = FALSE)

This worked for me even with nlsLM, too. The idea, too, behind coef(nls_model) is to use the coefficients of your successful model as the starting values in the geom_line so you get the same model. Just make sure you use y and x in the formula inside geom_line.