2010-04-14 12 views
15

최소 수직 제곱 회귀선이있는 플롯과 회귀 직선에 데이터 포인트를 연결하는 선분을 작성하는 데 관심이 있습니다. 여기에 수직 오프셋이라는 그래픽에 나와 있습니다. http://mathworld.wolfram.com/LeastSquaresFitting.html alt text http://mathworld.wolfram.com/images/eps-gif/LeastSquaresOffsets_1000.gif최소 제곱 회귀 그래프에서 최소 제곱 회귀 그래프를 그립니다.

나는 플롯 및 회귀 선은 여기 다있다 :

## 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") 

내가 수직 오프셋을 수행하는 루프 세그먼트 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) 
} 

지금 바로 전화 세그먼트 : 결과는 (플롯의 x 단위와 y 단위가 같은 체감을 가지고 등각 스케일을 보장하지 않는 한 수직 보이지 않는 것

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) 

주). pty="s"을 사용하여 사각형 플롯을 만들고 xlimylim을 같은 범위로 설정하면됩니다.

+0

완벽한, 감사합니다. –