【问题标题】:Plotting a line of best fit from where data starts to where data ends in R绘制一条从数据开始到数据在 R 中结束的最佳拟合线
【发布时间】:2023-03-31 01:17:02
【问题描述】:

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

abline(lm(y~x))

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

非常感谢!

【问题讨论】:

  • 查看 ggplot2 包中的 stat_smooth。本页示例http://docs.ggplot2.org/0.9.3.1/geom_abline.html
  • 只是为了澄清 abline 将穿过 Y 轴,否则严格来说它不能被视为一个。想一想。

标签: r plot lm


【解决方案1】:

一种解决方案是使用lines() 并对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

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-19
    • 1970-01-01
    • 2018-03-26
    • 2017-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多