[R] Regression line limited by the rage of values

Marc Schwartz (via MN) mschwartz at mn.rr.com
Wed May 24 19:04:33 CEST 2006


On Wed, 2006-05-24 at 18:51 +0200, Andreas Svensson wrote:
> Hi
> 
> In R, using  plot(x,y)   followed by abline(lm(y~x)) produces a graph 
> with a regression line spanning the whole plot . This means that the 
> line extends beyond the swarm of data points to the defined of default  
> plot region. With par(xpd=T) it will span the entire figure region. But 
> how can I limit a regression line to the data range, i.e between  
> (xmin,ymin) and  (xmax,ymax)?
> 
> Sorry for not knowing the lingo here. If you don't understand the 
> question, please run the following script:
> 
> x1<-c(1,2,3,4)
> x2<-c(5,6,7,8)
> y1<-c(2,4,5,8)
> y2<-c(10,11,12,16)
> plot(x1,y1,xlim=c(0,10),ylim=c(0,20),col="blue")
> points(x2,y2,col="red")
> abline(lm(y1~x1),col="blue")
> abline(lm(y2~x2),col="red")
> 
> The resulting plot isn't very informative. There is no overlap in the 
> two groups of data, yet the two ablines overlap.
> I instead  want the blue line to go from (1,2) to (4,8) and the red line 
> from (5,10) to (8,16).
> 
> So, how can I constrain the abline to the relevant region, i.e stop 
> abline from extrapolating beyond the actual range of data.
> Or should I use a function line 'lines' to do this?
> 
> Cheers
> Andres

Try this instead of the two abline()'s:

  lines(x1, fitted(lm(y1 ~ x1)), col = "blue")

  lines(x2, fitted(lm(y2 ~ x2)), col = "red")

The function fitted() will extract the model fitted y values from the
lm() model object.

See ?lines and ?fitted

HTH,

Marc Schwartz



More information about the R-help mailing list