在python中绘制正交距离

问题描述 投票:0回答:2

给定一组点和一条2D线,我想绘制每个点和该线之间的正交距离。有什么建议吗?

python numpy matplotlib data-visualization
2个回答
0
投票

y = m*x + b的形式查找给定线的方程式,其中m是斜率,b是y轴截距。垂直线的斜率是您已知斜率(即m2 = -1/m)的负逆。使用给定的点和新的斜率m2来获得与通过您的点的给定线垂直的线的方程。将第二行设置为与第一行相等,并求解xy。这是两条线相交的地方。获取相交点之间的差并找到幅度以确定给定线与给定点之间的距离:

distance = ((x2 - x)**2 + (y2 - y)**2)**0.5

其中[x2, y2]是给定点,[x, y]是交点。

更确切地说,生成了以下图像,以下面的示例代码来说明此技术:

enter image description here

import matplotlib.pyplot as plt
import numpy as np

# points follow [x, y] format

line_point1 = [2, 3]
line_point2 = [6, 8]

random_point = [-6, 5]

def line(x, get_eq=False):
    m = (line_point1[1] - line_point2[1])/(line_point1[0] - line_point2[0])
    b = line_point1[1] - m*line_point1[0]
    if get_eq:
        return m, b
    else:
        return m*x + b

def perpendicular_line(x, get_eq=False):
    m, b = line(0, True)
    m2 = -1/m
    b2 = random_point[1] - m2*random_point[0]
    if get_eq:
        return m2, b2
    else:
        return m2*x + b2

def get_intersection():
    m, b = line(0, True)
    m2, b2 = perpendicular_line(0, True)
    x = (b2 - b) / (m - m2)
    y = line(x)
    return [x, y]

domain = np.linspace(-10, 10)

plt.figure(figsize=(8, 9))
plt.plot(domain, [line(x) for x in domain], label='given line')
plt.plot(random_point[0], random_point[1], 'ro', label='given point')
plt.plot(domain, [perpendicular_line(x) for x in domain], '--', color='orange', label='perpendicular line')
intersection = get_intersection()
plt.plot(intersection[0], intersection[1], 'go', label='intersection')
plt.plot([intersection[0], random_point[0]], [intersection[1], random_point[1]], color='black', label='distance')
plt.legend()
plt.grid()
plt.show()

distance = ((random_point[0] - intersection[0])**2 + (random_point[1] - 
intersection[1])**2)**0.5
print(distance)

0
投票

这更像是一个数学问题。@jacob所说的是使用坐标几何的完美解决方案。如果您更喜欢使用向量数学(因此将numpy数组用作向量),则可以这样处理:

考虑直线的矢量方程:L = A + q lq是一个自由参数,我们希望找到它)您的点的位置向量:P正交条件(只是点积为零):L。 P = 0因此,A + q l)。 P = 0q =-(A。P / l。P(粗体表示vector,粗体小表示unit vector,其他均为标量)

我们找到了q;将q替换为直线的向量方程式可得出该点的位置向量,该点与从直线上放置的点的垂线相交。现在只需找到两点之间的距离,这就是差向量的大小:

d = | P-L(q)|

numpy实现非常简单:

L = A + lambda q: q*l                    // define the line as a function of q

q = - numpy.dot(A, P)/numpy.dot(l, P)    // find q subject to condition
d = numpy.linalg.norm(P - L(q))          // find the norm of the difference vector

此方法的优点是,它也适用于N维。这是resource,用于线的矢量方程。

© www.soinside.com 2019 - 2024. All rights reserved.