在R中的最小二乘回归图中绘制垂直偏移

D W*_*D W 16 statistics plot r linear-regression least-squares

我有兴趣制作一个带有最小二乘回归线和连接数据点与回归线的线段的图,如图所示,称为垂直偏移: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")
Run Code Online (Sandbox Code Playgroud)

我应该使用某种for循环和细分http://www.iiap.res.in/astrostat/School07/R/html/graphics/html/segments.html来做垂直偏移吗?有更有效的方法吗?如果可能,请提供一个示例.

Ani*_*iko 19

首先需要弄清楚垂直段基础的坐标,然后调用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)
}
Run Code Online (Sandbox Code Playgroud)

现在只需呼叫段:

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)
Run Code Online (Sandbox Code Playgroud)

请注意,除非确保绘图的x单位和y单位具有相同的表观长度(等距刻度),否则结果将不会垂直.你可以通过使用pty="s"得到一个方形图并设置xlimylim相同的范围来做到这一点.