[R] How to set the limit of abline (regression line of lm)

Gavin Simpson gavin.simpson at ucl.ac.uk
Mon Sep 20 12:57:36 CEST 2010


On Mon, 2010-09-20 at 17:31 +0800, elaine kuo wrote:
> Dear List,
> 
> 
> 
> I ran a regression model using lm and produced a regression line using
> abline.
> 
> 
> The line ranges from -20 to 20 in x axis,
> 
> and the section I only want is from -20 to 0.
> 
> 
> 
> Please kindly advise any function in abline () to set the range of x axes.

You can't; these are already set by the plot, and abline only *adds* to
the plot. You need to think about this a different way. What you want
are the model predictions for points spread over the range (-20, 0]. So
set up a new data set of 'x' values and use predict() to generate the
appropriate 'y' values.

Here's an example:

set.seed(123)
dat <- data.frame(x = sample(seq(-20, 20, length = 100)))
dat <- within(dat, y <- 8 + (1.8 * x) + (10 * rnorm(100)))
mod <- lm(y ~ x, data = dat)

## now plot the data
plot(y ~ x, data = dat)

## now predict 50 values spread evenly on range (-20, 0]
newdat <- data.frame(x = seq(-20, 0, length = 50))
newdat <- within(newdat, ypred <- predict(mod, newdat))

## add these predictions as a line to the plot
lines(ypred ~ x, data = newdat, col = "red", lwd = 2)

HTH

G

> Thank you
> 
> 
> 
> Elaine
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

-- 
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%
 Dr. Gavin Simpson             [t] +44 (0)20 7679 0522
 ECRC, UCL Geography,          [f] +44 (0)20 7679 0565
 Pearson Building,             [e] gavin.simpsonATNOSPAMucl.ac.uk
 Gower Street, London          [w] http://www.ucl.ac.uk/~ucfagls/
 UK. WC1E 6BT.                 [w] http://www.freshwaters.org.uk
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%



More information about the R-help mailing list