首页 > 解决方案 > 在python中绘制正交距离

问题描述

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

标签: pythonnumpymatplotlibdata-visualization

解决方案


以斜率和y 截距的形式y = m*x + b找到给定线的方程。垂直线的斜率是已知斜率的负倒数(即)。使用给定点和新斜率来获得垂直于通过您的点的给定线的线的方程。设置第二行等于第一行并求解和。这是两条线相交的地方。获取交点之间的差异并找到大小以确定给定线和给定点之间的距离:mbm2 = -1/mm2xy

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

哪里[x2, y2]是给定点,[x, y]是交点。

更准确地说,生成了以下图像以使用以下示例代码说明此技术:

在此处输入图像描述

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)

推荐阅读