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 Thanks, Doug -- --------------------------------- Douglas M. Hultstrand, MS Senior Hydrometeorologist Metstat, Inc. Windsor, Colorado voice: 970.686.1253 email: dmhultst at metstat.com web: http://www.metstat.com
On Oct 8, 2009, at 3:39 PM, 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)Perhaps instead: plot(z, predict(fit), type="l") points(z,p) # not a very interesting exercise given the utter simplicity of the data, but it should point the way forward. -- David Winsemius, MD Heritage Laboratories West Hartford, CT
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 >
Hi Doug, you can add the fitted curve using the following general paradigm: ## Plotting the data plot(p~z) ## Defining grid of z values ## (100 values ensures a smooth curve in your case) zValues <- seq(min(z), max(z), length.out = 100) ## Adding predicted values corresponding to the grid values lines(zVal, predict(fit, data.frame(z = zValues))) Christian