Plot fitted line within certain range R

雨燕双飞 提交于 2019-12-03 05:40:44

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)

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

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

Dr.J

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)

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.


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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!