Question

I want to plot a regression line with (a = 0 and b = 1) and add the individual point deviations from this along with identifying the data point with name.

set.seed(123)
namelab <- paste ("ET", 1:10, sep = "")
xvar <- 1:10
yvar <- rnorm(10, 5, 5)
myd <- data.frame(namelab, xvar, yvar)
plot(xvar, yvar)
abline (a= 0, b = 1, col = "red", lty = 2)

Just manual sketch of my intention, I just labelled a single point just for example. The line drawn need a slim. enter image description here

Was it helpful?

Solution

dev.new(width=4, height=4)
plot(xvar, yvar, asp=1)

a = 0
b = 1

abline (a, b, col = "red", lty = 2)

myd$xint = with(myd, (b*yvar + xvar - b*a) / (b^2 + 1))
myd$yint = with(myd, (b*yvar + b*xvar + a) / (b^2 + 1))

with(myd, segments(xvar, yvar, xint, yint))
with(myd, text(xvar, yvar, labels=namelab, pos=3, cex=0.5))

enter image description here

OTHER TIPS

...and if you did want vertical as opposed to perpendicular offsets, here is a pretty straightforward option:

set.seed(123)
namelab <- paste ("ET", 1:10, sep = "")
xvar <- 1:10
yvar <- rnorm(10, 5, 5)

plot(xvar, yvar)
abline (a= 0, b = 1, col = "red", lty = 2)
segments(xvar,yvar,xvar,xvar)
text(xvar,yvar,namelab,pos=3)

enter image description here

For this to work for any value of a and b, you would use:

segments(xvar,yvar,xvar,((xvar*b)+a))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top