[R] Plotting nls

Ben Rich richmcb at gmail.com
Fri Aug 26 16:44:12 CEST 2005


To get nice looking plots you can use trellis plots from the lattice
package.  First you need:

library(lattice)

Then you can define a custom panel function that will overlay the
fitted curve on top of the data points in a different color (you just
need to do this once; the fit you want plotted is specified as an
argument):

pred.overlay.panel <- function(x, y, fit, ...)
{
   panel.grid()
   panel.xyplot(x, y, ...)
   form <- as.list(sys.call(-2))[[2]]$call$formula
   resp <- deparse(form[[2]])
   covar <- deparse(form[[3]])
   xx <- seq(min(x), max(x), len=101)
   newdat <- data.frame(xx)
   colnames(newdat) <- covar
   panel.superpose(xx, predict(fit, newdata=newdat),
       subscripts=1:length(xx), groups=factor(rep(2, length(xx)),
       levels=1:2), type="l", ...)
}

Finally, you use the custom panel function in a call to xyplot:

xyplot(y ~ x, data=sample, panel=pred.overlay.panel, fit=fit,
scales=list(x=list(log=TRUE)))


Note how you specify that you want the x-axis to be in log-scale with
the scales parameter.

Hope this helps.

Ben

On 8/26/05, Lanre Okusanya <ooo at buffalo.edu> wrote:
> Kindly excuse a non-statistician newbie attempting to wrestle with R.
> 
> This might be a relatively easy question, but I am trying to perform nls
> regression and plot the fitted function through the data superimposed on
> the raw data. from reading the R-help, Rtips et al, I am only able to do
> that by extracting the parameter values manually and using it to create
> the plot.
> 
> Is there an easier way to do this,  (I have ~60 Plots), obtain an r^2,
> and also plot the x axis in the log domain (any attempts I have tried
> have screwed up).
> 
> NLS script
> 
> fit<- nls(y~-emax*x^h/(ec50^h+x^h),
>        data= sample, start=list(emax=4,h=2,ec50=1))
> 
> summary(fit)
> 
> Thank you all for your help
> 
> Lanre Okusanya, Pharm.D.,BCPS
> UB/Pfizer Pharmacometrics Fellow
> University at Buffalo School of Pharmacy and Pharmaceutical Sciences
> 237 Cooke Hall
> Buffalo, NY 14260
> Email: ooo at buffalo.edu
> Tel: (716)645-2828 x 275
> Fax: (716)645-2886
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
>




More information about the R-help mailing list