python - 在python中绘制正交距离
问题描述
给定一组点和一条二维线,我想绘制每个点和线之间的正交距离。有什么建议么?
解决方案
以斜率和y 截距的形式y = m*x + b
找到给定线的方程。垂直线的斜率是已知斜率的负倒数(即)。使用给定点和新斜率来获得垂直于通过您的点的给定线的线的方程。设置第二行等于第一行并求解和。这是两条线相交的地方。获取交点之间的差异并找到大小以确定给定线和给定点之间的距离:m
b
m2 = -1/m
m2
x
y
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)
推荐阅读
- java - 如何修复使用evosuite生成测试用例时出现的NoClassDefFoundError错误?
- java - 从群组中获取 Facebook 帖子
- c# - 适用于 OWIN 自托管 Web API 的 Unity Lifetime Mangers
- sql - Sql 命令 Oracle
- java - 如何修复变量可能尚未初始化
- qt - Qt 库问题:无法将我创建的动态库链接到项目
- graph - NetworkX 与 GraphDB:它们有相似的用途吗?何时使用其中一种,何时一起使用?
- javascript - 在 Javascript 中展平对象数组的快速方法
- python - 数据框和数组之间的点积上的 TypeError
- haskell - 将带有两个参数的过滤器函数应用于由 Haskell 中带有一个参数的函数生成的列表