Dear list members, When I create a simple scatterplot with a regression line (se below) the line is automatically extrapolated outside the range of data points. Why is this and how can I prevent R from extrapolating the regression line? Thank you in advance, Johan model<-lm(Herb~Para) plot(Para,Herb) abline(model)
On 10/12/2006 9:41 AM, Johan A. Stenberg wrote:> Dear list members, > > When I create a simple scatterplot with a regression line (se below) the > line is automatically extrapolated outside the range of data points. Why > is this and how can I prevent R from extrapolating the regression line? > > Thank you in advance, > Johan > > model<-lm(Herb~Para) > plot(Para,Herb) > abline(model)abline draws a line, not a line segment. If you want a segment that stays within the data, you'll need something like this: model <- lm(Herb ~ Para) plot(Para, Herb) lines(Para, predict(model)) Note that if Para is not sorted, this may look a little strange, and it will look like a complete mess if you try to fit a polynomial. You can sort it (and Herb correspondingly) by o <- order(Para) Para <- Para[o] Herb <- Herb[o] Duncan Murdoch
On Thu, 2006-10-12 at 15:41 +0200, Johan A. Stenberg wrote:> Dear list members, > > When I create a simple scatterplot with a regression line (se below) the > line is automatically extrapolated outside the range of data points. Why > is this and how can I prevent R from extrapolating the regression line? > > Thank you in advance, > Johan > > model<-lm(Herb~Para) > plot(Para,Herb) > abline(model)Hi Johan, Simply predict over the range of your predictor (Para). As I don't have those data, the example below uses dummy data X <- rnorm(500) # dummy data Y <- X + rnorm(500) mod <- lm(Y ~ X) # fit model # regular sequence over range of predictor X newdat <- seq(min(X), max(X), length = 100) # predict Y for each of these new data points pred <- predict(mod, newdata = list(X = newdat)) # plot the results plot(Y ~ X) lines(pred ~ newdat, col = "red") HTH G -- %~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~% Gavin Simpson [t] +44 (0)20 7679 0522 ECRC & ENSIS, 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 %~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%
> When I create a simple scatterplot with a regression line (se below) the > line is automatically extrapolated outside the range of data points. Why > is this and how can I prevent R from extrapolating the regression line?ggplot does this by default: install.packages("ggplot") library(ggplot) qplot(Para, Herd, type=c("smooth","point"), method=lm) Regards, Hadley