0

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.

maycca
  • 3,848
  • 5
  • 36
  • 67
  • 2
    We don't have your data, but you can probably add `control=nls.control(maxiter=200)` to `method.args`. – Axeman Jun 21 '17 at 14:21
  • thank you @Axeman, I thought that could be control=nls.control(maxiter=200), I was just not sure how to correctly put it in ggplot script. I found it worked just directly placed in method.args = list(start=c(a=20, b=0.01), control=nls.control(maxiter=200)). Can you please post it as your answer? I added my answer as well to be able to display the final data. Thank you ! – maycca Jun 27 '17 at 07:45
  • Your answer with attribution is fine, thanks, you can accept it later. – Axeman Jun 27 '17 at 08:01

1 Answers1

1

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

maycca
  • 3,848
  • 5
  • 36
  • 67