Re: [R] Regression line limited by the rage of values

From: Greg Snow <>
Date: Thu 25 May 2006 - 07:33:20 EST

For single lines the usual method is to just use the lines or segments function, however I have been thinking that there may be some other uses for clipping within a plot region when adding info (abline, but others as well). So here is a first stab at a function to clip within the region, it needs the TeachingDemos package to work. I'll probably put in some more error checking, document it and include it in a future TeachingDemos release, but you are welcome to use it in the meantime.

For your case you would create your scatterplot the same as you already did, then add the lines like:

> clipplot( abline(lm(y1~x1),col="blue"), xlim=c(1,4) )
> clipplot( abline(lm(y2~x2),col="red"), xlim=c(5,8) )

Here is the function definition:

clipplot <- function(fun, xlim=par('usr')[1:2],

        ylim=par('usr')[3:4] ){
  old.par <- par(c('plt','xpd'))

  if( length(xlim) < 2 ) stop('xlim must be a vector with at least 2 elements')
  if( length(ylim) < 2 ) stop('ylim must be a vector with at least 2 elements')

  if( !require(TeachingDemos) ) stop('TeachingDemos package needed')

  xl <- range(xlim)
  yl <- range(ylim)

  pc <- cnvrt.coords(xl,yl)$fig



  box() # need to plot something to reset


Hope this helps,

Gregory (Greg) L. Snow Ph.D.
Statistical Data Center
Intermountain Healthcare
(801) 408-8111

-----Original Message-----
[] On Behalf Of Andreas Svensson
Sent: Wednesday, May 24, 2006 10:52 AM
Subject: [R] Regression line limited by the rage of values


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:


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?


______________________________________________ mailing list
PLEASE do read the posting guide!

______________________________________________ mailing list
PLEASE do read the posting guide!
Received on Thu May 25 07:51:08 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Thu 25 May 2006 - 08:10:59 EST.

Mailing list information is available at Please read the posting guide before posting to the list.