Alex Rivera | Logout

Plot fitted line within certain range R

Asked 2012-04-05T21:42:28.920
20

Using R, I would like to plot a linear relationship between two variables, but I would like the fitted line to be present only within the range of the data.

For example, if I have the following code, I would like the line to exist only from x and y values of 1:10 (with default parameters this line extends beyond the range of data points).

x <- 1:10
y <- 1:10
plot(x,y)
abline(lm(y~x))
Edit
Report

1 Answer

8

You can do this using predict.

You can predict on specific values of x (see ?predict)

x<-1:10
y<-1:10
plot(x,y)
new <- data.frame(x = seq(1, 5, 0.5))
lines(new$x, predict(lm(y~x), new))

enter image description here

answered 2012-04-05T22:05:25.387

Your Answer