Skip to content
Prev 215895 / 398500 Next

Adding regression lines to each factor on a plot when using ANCOVA

Steve,

Thanks for providing an example (which does, however need a bit of
tweaking; BTW, it's usually not a good idea to cbind your data
when what you really want is a data.frame).

Your guess about some clever way of using abline() is unfortunately
not correct - as the help page indicates, the slope and intercept
must be given as single values. So you will have to extract each
(intercept, slope) pair from the model coefficients and call abline()
on them. A convenient way to do this is to specify the model as

  mod <- lm(y ~ f/x + 0)

(which I first learned from MASS, the book).
Here f is your grouping variable.  As the book says,
this gives "separate regression models of the type 1 + x within
the levels of f".  The "+ 0" removes the usual intercept which is
replaced by individual intercepts for each level of f.

For your example this will give 12 intercepts as
the first 12 coefficients and 12 slopes as the remaining coefs.

Then you can use

  cof <- coef(mod)
  for(i in 1:12) abline(a=cof[i], b=cof[12 + i])

to plot the 12 lines.

  -Peter Ehlers
On 2010-04-01 16:21, Steven Worthington wrote: