【问题标题】:Regression Line to Data Points/ How to create vertical lines?回归线到数据点/如何创建垂直线?
【发布时间】:2014-06-23 00:56:31
【问题描述】:

如何在 R 中获得以下可视化效果(见下文): 让我们考虑一个简单的三点案例。

# Define two vectors
x <- c(12,21,54)
y <- c(2, 7, 11)

# OLS regression
ols <- lm(y ~ x)

# Visualisation
plot(x,y, xlim = c(0,60), ylim =c(0,15))    
abline(ols, col="red")

我想要的是,绘制从 OLS 线(红线)到点的垂直距离线。

【问题讨论】:

  • 我认为这是一个有用的问题。也许考虑将标题编辑为更容易搜索的内容,例如 Plot vertical lines between fitted/regression line to data points 或类似的内容。

标签: r plot visualization lines points


【解决方案1】:

ggplot2 可以很好地做到这一点

library(ggplot2)
set.seed(1)     
x<-1:10
y<-3*x + 2 + rnorm(10)
m<-lm(y ~ x)
yhat<-m$fitted.values
diff<-y-yhat     
qplot(x=x, y=y)+geom_line(y=yhat)+
       geom_segment(aes(x=x, xend=x, y=y, yend=yhat, color="error"))+
       labs(title="regression errors", color="series")

【讨论】:

    【解决方案2】:

    有一个更简单的解决方案:

    segments(x, y, x, predict(ols))
    

    【讨论】:

    • 这就像一个魅力!您还可以添加参数col="red" 使线条变为红色。 segments(x, y, x, predict(ols), col="red")
    【解决方案3】:

    如果你构建一个点矩阵,你可以使用 apply 来绘制这样的线:

    创建一个坐标矩阵:

    cbind(x,x,y,predict(ols))
    #   x  x  y          
    #1 12 12  2  3.450920
    #2 21 21  7  5.153374
    #3 54 54 11 11.395706
    

    这可以绘制为:

    apply(cbind(x,x,y,predict(ols)),1,function(coords){lines(coords[1:2],coords[3:4])})
    

    实际上是一个for 循环遍历矩阵的行并为每一行绘制一条线。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-27
      • 1970-01-01
      • 2019-09-21
      • 1970-01-01
      • 2022-11-14
      • 1970-01-01
      • 2014-07-07
      相关资源
      最近更新 更多