Plotting a line of best fit from where data starts to where data ends in R

依然范特西╮ 提交于 2019-12-25 06:38:10

问题


I am trying to plot a line of best fit on my dataset in R:

abline(lm(y~x))

However the line goes all the way through the entire graph. Is there anyway that I can configure the line so that it only covers the area where the data points are (similar to what you get in Excel)?

Many thanks!


回答1:


A solution would be to use lines() and have two predictions for both extremes of x.

See this example:

x <- rnorm(20)
y <- 5 + 0.4*x + rnorm(20)/10
dt <- data.frame(x=x, y=y)
ols1 <- lm(y ~ x, data=dt)
nd <- data.frame(x=range(x))    ## generate new data with the two extremes of x
plot(x, y)                      ## original scatter plot
lines(nd$x, predict(ols1, newdata=nd), col='orange')  ## line from two points

I hope that helps.



来源:https://stackoverflow.com/questions/23115746/plotting-a-line-of-best-fit-from-where-data-starts-to-where-data-ends-in-r

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