FAQ/reglineR - CBU statistics Wiki

Revision 9 as of 2012-02-16 11:45:03

Clear message
location: FAQ / reglineR

Putting user defined regression lines on scatterplots in R

One example where you may wish to insert two or more regression lines on a scatterplot is when you have groups whose line of best fit you wish to plot assuming they have the same slope (ie as assumed in an ANCOVA).

This is also covered in the regression graduate statistics talk. R is particularly good at this as it produces a legend which has both marker and line information to denote the different groups.

The code below takes a SPSS data file containing four columns denoting the Raven score (predictor) and WCST values (response) for each of two groups (controls and patients) and plots the two regression lines (one for each group) which have the same slope but different intercepts. The values of these coefficients can be obtained using a linear regression and entered into the plot using the 'abline' function.

This code puts the legend in the picture like [attachment:wcst.ppt this.]

library(foreign)
x <- read.spss("C:\\Documents and Settings\\peterw\\Desktop\\My Documents\\My Documents2\\JOHN D ANCOVA FOR WIKI\\JD PLOTS 25-1-12\\R PLOTS FORMAT2.sav")
attach(x)
plot(Raven1,WCST1,xlim=c(10,40),ylim=c(1,6),pch=1,,xlab="RCPM(Total Score)",ylab="WCST (Number of categories achieved)")
points(Raven2,WCST2,pch=4)
abline(a=-0.455,b=0.183,lty=2)
abline(a=-0.181,b=0.183,lty=1)
legend(x=28,y=2,c("Controls","Patients"), pch=c(4,1),lty=c(1,2))

The code below will put the legend outside (tot he right of) the plot.

library(foreign)
x <- read.spss("C:\\Documents and Settings\\peterw\\Desktop\\My Documents\\My Documents2\\JOHN D ANCOVA FOR WIKI\\JD PLOTS 25-1-12\\R PLOTS FORMAT2.sav")
attach(x)
par(xpd=TRUE, mar=par()$mar+c(0,0,0,4))
plot(Raven1,WCST1,xlim=c(10,40),ylim=c(1,6),pch=1,xlab="RCPM(Total Score)",ylab="WCST (Number of categories achieved)")
points(Raven2,WCST2,pch=4)
legend(x=41,y=5,c("Controls","Patients"), pch=c(4,1),lty=c(1,2),bty='n') 
par(xpd=FALSE)
abline(a=-0.455,b=0.183,lty=2)
abline(a=-0.181,b=0.183,lty=1)