2014-05-06 243 views
2

如何在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線(紅線)到點的垂直距離線。 enter image description here

+0

我覺得這是一個有用的問題。也許可以考慮將標題編輯爲更容易搜索的內容,例如「繪製擬合/迴歸線與數據點之間的垂直線」或其他類似內容。 – rmbaughman

回答

3

如果您構建點的矩陣,您可以使用適用於繪製這樣的線:

創建座標矩陣:

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循環遍歷矩陣的行併爲每行繪製一行。

+0

它超級棒!非常感謝。 –

5

您可以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") 

enter image description here

2

做到這一點真的很好有一個更簡單的解決方案:

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

這工作就像一個魅力!您也可以添加參數'col =「red」'使線條變紅。 '段(x,y,x,預測(ols),col =「紅色」)' – rvbarreto