Plot fitted line within certain range R

Thraupidae picture Thraupidae · Apr 5, 2012 · Viewed 40.2k times · Source

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))

Answer

Greg Snow picture Greg Snow · Apr 6, 2012

In addition to using predict with lines or segments you can also use the clip function with abline:

x <- 1:10
y <- 1:10
plot(x,y)
clip(1,10, -100, 100)
abline(lm(y~x))