绘制一条最合适的线,从R的数据开始到R的数据结束 [英] Plotting a line of best fit from where data starts to where data ends in R

查看:91
本文介绍了绘制一条最合适的线,从R的数据开始到R的数据结束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在R中的数据集上绘制一条最合适的线:

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

abline(lm(y〜x))

abline(lm(y~x))

但是,这条线一直贯穿整个图形.无论如何,我是否可以配置该行,使其仅覆盖数据点所在的区域(类似于您在Excel中获得的内容)?

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

非常感谢!

推荐答案

一种解决方案是使用lines(),并对x的两个极端都有两个预测.

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

请参见以下示例:

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

我希望能帮上忙.

这篇关于绘制一条最合适的线,从R的数据开始到R的数据结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆