Greetings. Is there any way to get R to take a regression model object and draw a plot of the regression function? How about overlaying that plot over a scatterplot of the actual data? Thanks in advance for any help anyone can provide. Aaron ----- Aaron Solomon?? (??ben Saul Joseph??) ??Adelman E-mail??: ??adelmaas at musc.edu Web site??: ??http??://??people.musc.edu??/??~adelmaas??/?? AOL Instant Messenger?? & ??Yahoo??! ??Messenger: ??Hiergargo
On Wed, 3 Nov 2004 10:12:53 -0500, adelmaas at MUSC.EDU wrote :>Greetings. > >Is there any way to get R to take a regression model object and draw a >plot of the regression function? How about overlaying that plot over a >scatterplot of the actual data? Thanks in advance for any help anyone >can provide.Lots of functions in R can adapt themselves to complex objects in a sensible way. (These are called generic functions.) The usual way to draw a straight line would be to use abline(), and it can handle linear model objects: # fake some data x <- 1:10 y <- rnorm(10) # fit it and plot it. fit <- lm(y ~ x) plot(x, y) abline(fit) If you've fit a more complicated model (e.g. a quadratic), you need a different method (because abline only works on straight lines). Then use fit <- lm(y ~ x + I(x^2)) plot(x, y) lines(predict(fit)) (This would work for the original one, too.) Duncan Murdoch
adelmaas at MUSC.EDU wrote:> Greetings. > > Is there any way to get R to take a regression model object and draw a > plot of the regression function? How about overlaying that plot over a > scatterplot of the actual data? Thanks in advance for any help anyone > can provide. > > Aaron >Hi Aaron, What type of "regression function" are your referring to? Linear model? Non-linear model? The term "regression" is to ambiguous to really answer your question. However, typically you should be able to do something like: fit <- lm(y ~ x) yhat <- predict(fit) plot(x, y, ylim = range(c(y, yhat))) lines(x, yhat) If you are not using lm please provide more information than you already have. You should read "Introduction to R" or any of the recommended texts listed on the R website. Also read the posting guide. --sundar
Welcome to R. You can start by looking at the predict function for the regression model you are using (e.g., ?predict.lm if you are using a linear model). Then do something like so: data(cars) cars.lm <- lm(dist ~ speed, cars) dist.pred <- predict(cars.lm) plot(cars$speed, cars$dist, ylim = c(-2, 120)) lines(cars$speed, dist.pred, col = "red", lwd = 2) HTH, Andy
Regarding plotting a regression fit - for a simple linear regression model the abline function adds the fitted line to a plot. plot(optden ~ carb, Formaldehyde) abline(fm1 <- lm(optden ~ carb, Formaldehyde))