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))
Hack-R
  • 22,422
  • 14
  • 75
  • 131
Thraupidae
  • 665
  • 2
  • 5
  • 14

5 Answers5

28

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))
Greg Snow
  • 48,497
  • 6
  • 83
  • 110
  • 6
    +1, because it works with any line, also abline(), without using the hack with predict(). This way one can, e.g., also trim ablines that extend to the margins of a plot, but only to one side, e.g. to the right, not to the left. – pfifas Jan 27 '15 at 12:40
  • 1
    This is a far better answer than the accepted one. Much simpler, and actually operates on the visual representation, as desired, rather than making some weird new line representation using `predict` – setholopolus Jan 18 '20 at 15:25
18

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

plot(x,y)
lines(x=X, y=Y)
Josh O'Brien
  • 159,210
  • 26
  • 366
  • 455
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

Etienne Low-Décarie
  • 13,063
  • 17
  • 65
  • 87
4

The plotrix library has the ablineclip() function for just this:

x <- 1:10
y <- 1:10
plot(x,y)
ablineclip(lm(y~x),x1=1,x2=5)
Ben
  • 1,414
  • 2
  • 13
  • 18
Dr.J
  • 41
  • 2
0

An alternative is to use the segments function (doc here).

Say you estimated the line, and you got an intercept of a and a slope of b. Thus, your fitted function is y = a + bx.

Now, say you want to show the line for x between x0 and x1. Then, the following code plots your line:

# inputs

a <- 0.5
b <- 2

x0 <- 1
x1 <- 5

# graph

plot(c(0,5), c(0,5), type = "n", xlab = "", ylab = "", bty='l')
segments(x0, a+b*x0, x1, a+b*x1)

Simply replace the values of a, b, x0, x1 with those of your choosing.

enter image description here


For those like me who came to this question wanting to plot a line for an arbitrary pair of numbers (and not those that fit a given regression), the following code is what you need:

plot(c(0,5), c(0,5), type = "n", xlab = "", ylab = "", bty='l')
segments(x0, yo, x1, y1)

Simply replace the values of x0, y0, x1, y1 with those of your choosing.

luchonacho
  • 6,759
  • 4
  • 35
  • 52