Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R draw (abline + lm) line-of-best-fit through arbitrary point

I am trying to draw a least squares regression line using abline(lm(...)) that is also forced to pass through a particular point. I see this question is related, but not quite what I want. Here's an example:

test <- structure(list(x = c(0, 9, 27, 40, 52, 59, 76), y = c(50, 68, 
79, 186, 175, 271, 281)), .Names = c("x", "y"))

# set up an example plot
plot(test,pch=19,ylim=c(0,300),
     panel.first=abline(h=c(0,50),v=c(0,10),lty=3,col="gray"))

# standard line of best fit - black line
abline(lm(y ~ x, data=test))

# force through [0,0] - blue line
abline(lm(y ~ x + 0, data=test), col="blue")

This looks like:

enter image description here

Now how would I go about forcing a line through the marked arbitrary point of (x=10,y=50) while still minimising the distance to the other points?

# force through [10,50] - red line
??
like image 401
thelatemail Avatar asked Apr 22 '13 06:04

thelatemail


2 Answers

A rough solution would be to shift the origin for your model to that point and create a model with no intercept

nmod <- (lm(I(y-50)~I(x-10) +0, test))

abline(predict(nmod, newdata = list(x=0))+50, coef(nmod), col='red')

enter image description here

like image 168
mnel Avatar answered Nov 05 '22 22:11

mnel


You can modify the formula for lm() and offset the data:

p=10
q=50

abline(lm(I(y-q) ~ I(x-p) + 0, data=test), col="red")
like image 29
Nishanth Avatar answered Nov 05 '22 21:11

Nishanth