一、点到过原点直线投影坐标简要说明

\(~\)

\(~\)

已知过原点直线的方程为\(y=ax\),其中\(y\)为因变量,\(x\)为自变量,\(a\)为斜率。
\(~\)

\(~\)

已知点A的坐标是\((x_0,y_0)\),垂足点\(C(x_1,y_1)\)为点A在直线\(y=ax\)上的投影坐标(见图1)。经过点A且与直线\(y=ax\)垂直的线性方程的斜率为\(-\dfrac{1}{a}\),垂线的方程为\(y=-\dfrac{1}{a}x+b\),垂线经过点A\((x_0,y_0)\),垂线的截距为\(b=y_0+\dfrac{1}{a}x_0\)

\(~\)
垂足\(C(x_1,y_1)\)经过直线\(y=ax\)和垂线\(y=-\dfrac{1}{a}x+b\),代入联立方程得\(x_1=\dfrac{ab}{1+a^2}\),\(y_1=\dfrac{a^2b}{1+a^2}\)

图1:点在直线上的投影

二、R语言代码实现直线旋转后的垂足与距离情况

> # 画垂足小角标的函数,参考处:https://stackoverflow.com/questions/32903079/add-perpendicular-symbol-to-a-plot
> 
> perpendicular<-function(x,y,x1,y1,x2,y2,k){ 
+   #points(x,y,col="red",pch=16);points(x1,y1,pch=16);points(x2,y2,pch=16)
+   m1<-c(x1-x,y1-y);m2<-c(x2-x,y2-y)   #two vector of the line 
+   m1<-m1/sqrt(sum(m1^2));m2<-m2/sqrt(sum(m2^2))   #standardlized the vector
+   #construct the shape I want
+   xx1<-c(x,y)+k*m1
+   xx2<-c(x,y)+k*m2
+   xx3<-c(x,y)+k*(m1+m2)
+   lines(c(xx1[1],xx3[1]),c(xx1[2],xx3[2]),lty=2,col="red")
+   lines(c(xx2[1],xx3[1]),c(xx2[2],xx3[2]),lty=2,col="red")
+ }
> 
> #利用以下批注的循环可以实现多幅图的生成
> # png(file="example%02d.png", width=800, height=800)
> #  for (i in seq(0,2*pi,length.out=20)) {
> # slope=tan(i)
> slope=3#循环时要把这条语句替换成上一条
> x<-1:10
> y<-slope*x
> m<-lm(y ~ x)
> yhat <- m$fitted.values
> a <- coef(m)[2]
> A <- c(10,4)
> x0 <- A[1]
> y0 <- A[2]
> b <- y0+1/a*x0 
> x1 <- a*b/(a^2+1)
> y1 <- (a^2*b)/(a^2+1)
> 
> d=sqrt((x0-x1)^2+(y0-y1)^2)
> 
> plot(x0,y0,frame.plot = FALSE,xlim = c(-20,20),ylim = c(-20,20),
+      pch = 19,col="darkgreen", cex=1.5,xlab = "x",
+      ylab = "y",axes = FALSE,asp = 1)
> axis(1, pos=0,at=seq(-20,20,5),hadj=-0.2,font=2,col="red")
> axis(2, at = seq(-20,20,5),pos=0,hadj=-0.2,font=2,col="red")
> 
> abline(m,col = "blue",lwd=1.5)
> segments(x0,y0,x1,y1,col="black",lty=2,lwd=1.5)
> text(20-5,20-1,paste("距离:",round(d,2)))
> perpendicular(x1,y1,x0,y0,0,0,1)

> # }
> #  dev.off()
> #利用以下函数可以把多幅png图片组合起来,形成动态的gif图
> # library(magick)
> # library(magrittr)
> # list.files( pattern = 'example??.png', full.names = TRUE) %>% 
> # image_read() %>% 
> # image_join() %>% 
> # image_animate(fps=4) %>% 
> # image_write("point2line.gif")  

最后的结果见图2

图2:点在不同直线上的投影动态展示