[R] Newbie question: plotting regression models

Duncan Murdoch murdoch at stats.uwo.ca
Wed Nov 3 16:30:41 CET 2004


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




More information about the R-help mailing list