[R] Plot nls line on plot?

Peter Ehlers
Thu, 08 Oct 2009 23:47:05 -0000

Douglas M. Hultstrand wrote:
> Hello,
>
> I have a non-linear function (exponential) that I am trying to display
> the line with the data in a plot, is there a command similar to abline()
> for the function I created, if not what is the best way to display the
> fitted line.  Example code below.
>
> ### Example
> z <- c(1,10,15,20,25,30,35,40,45,50,55,60)
> p <- c(.02,.08,.2,.45,1.03,2.36,5.37,12.24,27.85,63.39,144.27,328.35)
> cnt <- length(z)
>
> fit <- nls(p~(b*exp(m*z)), start=list(m=.1645,b=.017),
> control=list(maxiter=200))
> plot(p~z)
> # want to add fit/line to plot
>

You could use curve() with the parameter estimates from fit:
co <- coef(fit)
f <- function(x, m, b) {b*exp(m*x)}
curve(f(x, m=co["m"], b=co["b"], add=TRUE)

  -Peter Ehlers

> Thanks,
> Doug
>