16

ここで垂直オフセットと呼ばれる図に示されているように、最小二乗回帰線と、データポイントを回帰線に接続する線分を使用してプロットを作成することに興味があり ます - Wolfram Web リソース: wolfram.com )代替テキスト

ここでプロットと回帰直線を作成しました:

## 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を使用する必要がありますか? より効率的な方法はありますか?可能であれば例を挙げてください。

4

1 に答える 1

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

セグメントを呼び出すだけです。

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"して正方形のプロットを取得し、同じ範囲に設定xlimします。ylim

于 2010-04-14T18:42:13.573 に答える