Graphing perpendicular offsets in a least squares regression plot in R

倾然丶 夕夏残阳落幕 提交于 2019-11-29 21:05:57

You first need to figure out the coordinates for the base of the perpendicular segments, then call the segments function which can take vectors of coordinates as inputs (no need for a loop).

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)
}

Now just call segments:

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)

Note that the results will not look perpendicular unless you ensure that the x-unit and y-unit of your plot have the same apparent length (isometric scales). You can do that by using pty="s" to get a square plot and set xlim and ylim to the same range.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!