# [R] Trendline for a subset of data

Greg Snow Greg.Snow at imail.org
Mon Oct 12 20:57:35 CEST 2009

```Others have show how to use the segments function, but this can also be done using the original abline function along with the clip function.  Here is an example:

plot( iris\$Petal.Width, iris\$Petal.Length,
col=c('red','green','blue')[iris\$Species])

tmp <- levels(iris\$Species)
tmp2 <- par('usr')

for(i in 1:3) {
fit <- lm( Petal.Length ~ Petal.Width, data=iris, subset= Species==tmp[i] )
tmpx <- with(iris, Petal.Width[ Species==tmp[i] ] )
clip( min(tmpx), max(tmpx), tmp2[3], tmp2[4] )
abline( fit, col=c('red','green','blue')[i] )
}

Hope this helps,

--
Gregory (Greg) L. Snow Ph.D.
Statistical Data Center
Intermountain Healthcare
greg.snow at imail.org
801.408.8111

> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of Steve Murray
> Sent: Friday, October 09, 2009 3:51 AM
> To: r-help at r-project.org
> Subject: [R] Trendline for a subset of data
>
>
> Dear all,
>
> I am using abline(lm ...) to insert a linear trendline through a
> portion of my data (e.g. dataset[,36:45]). However, I am finding that
> whilst the trendline is correctly displayed and representative of the
> data portion I've chosen, the line continues to run beyond this data
> segment and continues until it intersects the vertical axes at each
> side of the plot.
>
> How do I display the line so that it only runs between point 36 and 45
> (as shown in the example above) as doesn't continue to display a line
> throughout the rest of the plot space?
>
> Many thanks,
>
> Steve
>
> _________________________________________________________________