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

Steven Worthington steven.worthington at gmail.com
Fri Apr 2 00:21:18 CEST 2010

Dear R users,

i'm using a custom function to fit ancova models to a dataset. The data are
divided into 12 groups, with one dependent variable and one covariate. When
plotting the data, i'd like to add separate regression lines for each group
(so, 12 lines, each with their respective individual slopes). My 'model1'
uses the group*covariate interaction term, and so the coefficients to plot
these lines should be contained within the 'model1' object (there are 25
coefficients and it looks like I need the last 12). The problem is I can't
figure out how to extract the relevant coefficients from 'model1' and add
them using abline. I imagine there's some way of using the relevant slopes 


together with the intercept, but I can't quite get it right. Can anyone
offer a suggestion as to how to go about this? Ideally, What i'd like is to
plot each regression line in the same color as the group to which it

I've provided an example with dummy data below



# ===========================================================
# hypothetical data
species <-
beak.lgth <-
mass <-
dataset <- cbind(groups, beak.lgth, mass)

# ANCOVA function
anc <- function(variable, covariate, group){
	# transform data
	lgVar <- log10(variable)
	lgCov <- log10(covariate)
	# separate regression lines for each group
	model1 <- lm(lgVar ~ lgCov + group + lgCov:group) 
		model1.summ <- summary(model1) 
		model1.anv <- anova(model1)
	# separate regression lines for each group, but with the same slope
	model2 <- lm(lgVar ~ lgCov + group) 
		model2.summ <- summary(model2) 
		model2.anv <- anova(model2)
	# same regression line for all groups
	model3 <- lm(lgVar ~ lgCov) 
		model3.summ <- summary(model3) 
		model3.anv <- anova(model3)
	compare <- anova(model1, model2, model3) # compare all models
	# plots
	boxplot(lgVar ~ group, col="darkgoldenrod1")
	# plot the variate and covariate by group
	plot(lgVar ~ lgCov, pch=as.numeric(group), col=as.numeric(group)) 
		legend("topleft", inset=0, legend=as.character(unique(group)),
		pch=as.numeric(unique(group)), pt.cex=1.5)
		abline(model1) # Need separate regression lines here
	list(model_1_summary=model1.summ, model_1_ANOVA=model1.anv,
		model_2_ANOVA=model2.anv, model_3_summary=model3.summ,
model_3_ANOVA=model3.anv, model_comparison=compare)

# call function
anc(beak.lgth, mass, species)
# ===========================================================

View this message in context: http://n4.nabble.com/Adding-regression-lines-to-each-factor-on-a-plot-when-using-ANCOVA-tp1748654p1748654.html
Sent from the R help mailing list archive at Nabble.com.

More information about the R-help mailing list