Search code examples
rplotnls

How get plot from nls in R?


In R I use nls to do a nonlinear least-squares fit. How then do I plot the model function using the values of the coefficients that the fit provided?

(Yes, this is a very naive question from an R relative newbie.)


Solution

  • Using the first example from ?nls and following the example I pointed you to line by line achieves the following:

    #This is just our data frame
    DNase1 <- subset(DNase, Run == 1)
    DNase1$lconc <- log(DNase1$conc)
    #Fit the model
    fm1DNase1 <- nls(density ~ SSlogis(lconc, Asym, xmid, scal), DNase1)
    
    #Plot the original points
    # first argument is the x values, second is the y values
    plot(DNase1$lconc,DNase1$density)
    
    #This adds to the already created plot a line
    # once again, first argument is x values, second is y values
    lines(DNase1$lconc,predict(fm1DNase1))
    

    The predict method for a nls argument is automatically returning the fitted y values. Alternatively, you add a step and do

    yFitted <- predict(fm1DNase1)
    

    and pass yFitted in the second argument to lines instead. The result looks like this:

    enter image description here

    Or if you want a "smooth" curve, what you do is to simply repeat this but evaluate the function at more points:

    r <- range(DNase1$lconc)
    xNew <- seq(r[1],r[2],length.out = 200)
    yNew <- predict(fm1DNase1,list(lconc = xNew))
    
    plot(DNase1$lconc,DNase1$density)
    lines(xNew,yNew)