Search code examples
rplotggplot2nls

Geom_smooth: When groups added, number of iterations exceeded maximum of 50?


I am pretty new in modelling. I have three groups of data (by period), which I want to display by lines over scatter plot.

I figured out how to put my method and formula in geom_smooth, and I am able to display a single line.

However, when I want to add lines per group, which could be accomplished by ggplot(.., aes(..,group = period)), I've got back a Warning:

Warning message:
Computation failed in `stat_smooth()`:
number of iterations exceeded maximum of 50

and the line is not displayed.

My working code:

ggplot(tab, aes(x=distance, y=grad)) + #
  geom_point() + theme_bw() +
  geom_smooth(method = "nls",
              formula = y ~ a*x^(-b),
              method.args = list(start=c(a=20, b=0.01)),  # 
              se = F)

results:

enter image description here

Code providing error (with added group = period in aes), and not displaying lines per group:

ggplot(tab, aes(x=distance, y=grad, group = period)) + #
  geom_point() + theme_bw() +
  geom_smooth(method = "nls",
              formula = y ~ a*x^(-b),
              method.args = list(start=c(a=20, b=0.01)),  # 
              se = F)

Do you have some ideas how can I increase the number of iteration in ggplot2 by geom_smooth function? I found some information to increase number of iteration by control=nls.control(maxiter=200) https://stat.ethz.ch/pipermail/r-help/2006-June/107606.html relative to R base modelling, but I can't find solution or directions for ggplot2.


Solution

  • Based on @Axeman comment, I added the control=nls.control(maxiter=200) to the

    method.args = list(start=c(a=20, b=0.01), 
                                     control=nls.control(maxiter=200))
    

    The whole script is thus:

    ggplot(tab, aes(x=distance, y=grad, group = period, col = period)) + #
      geom_point(col = "grey") + theme_bw() +
      geom_smooth(method = "nls",
                  formula = y ~ a*x^(-b),
                  method.args = list(start=c(a=20, b=0.01), 
                                     control=nls.control(maxiter=200)),  # 
                  se = F)
    

    And the result is:enter image description here