2010-04-14 71 views
15

我有興趣用最小二乘迴歸直線和連接數據點與迴歸線的線段繪製圖,如圖所示的垂直偏移圖: http://mathworld.wolfram.com/LeastSquaresFitting.html alt text http://mathworld.wolfram.com/images/eps-gif/LeastSquaresOffsets_1000.gif在R中的最小二乘迴歸圖中繪製垂直偏移圖

我已經情節和迴歸線在這裏完成:

## Dataset from http://www.apsnet.org/education/advancedplantpath/topics/RModules/doc1/04_Linear_regression.html 

## Disease severity as a function of temperature 

# Response variable, disease severity 
diseasesev<-c(1.9,3.1,3.3,4.8,5.3,6.1,6.4,7.6,9.8,12.4) 

# Predictor variable, (Centigrade) 
temperature<-c(2,1,5,5,20,20,23,10,30,25) 

## For convenience, the data may be formatted into a dataframe 
severity <- as.data.frame(cbind(diseasesev,temperature)) 

## Fit a linear model for the data and summarize the output from function lm() 
severity.lm <- lm(diseasesev~temperature,data=severity) 

# Take a look at the data 
plot(
diseasesev~temperature, 
     data=severity, 
     xlab="Temperature", 
     ylab="% Disease Severity", 
     pch=16, 
     pty="s", 
     xlim=c(0,30), 
     ylim=c(0,30) 
) 
abline(severity.lm,lty=1) 
title(main="Graph of % Disease Severity vs Temperature") 

我應該使用某種形式的for循環和段http://www.iiap.res.in/astrostat/School07/R/html/graphics/html/segments.html做垂直偏移?有沒有更高效的方法?請儘可能提供一個例子。

回答

16

您首先需要計算出垂直線段底部的座標,然後調用segments函數,該函數可以將座標向量作爲輸入(不需要循環)。

perp.segment.coord <- function(x0, y0, lm.mod){ 
#finds endpoint for a perpendicular segment from the point (x0,y0) to the line 
# defined by lm.mod as y=a+b*x 
    a <- coef(lm.mod)[1] #intercept 
    b <- coef(lm.mod)[2] #slope 
    x1 <- (x0+b*y0-a*b)/(1+b^2) 
    y1 <- a + b*x1 
    list(x0=x0, y0=y0, x1=x1, y1=y1) 
} 

現在只需撥打段:

ss <- perp.segment.coord(temperature, diseasesev, severity.lm) 
do.call(segments, ss) 
#which is the same as: 
segments(x0=ss$x0, x1=ss$x1, y0=ss$y0, y1=ss$y1) 

注意,結果將不看垂直,除非您確保情節的X單元和Y單元具有相同的外觀長度(等距量表)。你可以通過使用pty="s"來獲得方形圖並將xlimylim設置爲相同的範圍。

+0

完美,謝謝。 – 2010-04-16 17:28:08