view raw
Thraupidae Thraupidae - 8 months ago 57
R Question

Plot fitted line within certain range R

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


Instead of using abline(), (a) save the fitted model, (b) use predict.lm() to find the fitted y-values corresponding to x=1 and x=10, and then (c) use lines() to add a line between the two points:

f <- lm(y~x)
X <- c(1, 10)
Y <- predict(f, newdata=data.frame(x=X))

lines(x=X, y=Y)