计算直线的角度(度)

2024-04-25 09:28:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图确定两点直线的角度,我在网上遇到了许多解决方法,但没有一个对我有用,考虑这段代码

import matplotlib.pyplot as plt
data = np.array([7405.,7447.4,7433.99,7410.,7443.15,7429.4,7590.03,7550.,7566.32,7619.62,7549.71,7551.8,7530,7522.99,7499.75,7453.99,7542.16,7564.,7552.77,7552])
y = [7606.672474,7570.240928]
plt.plot(data)
plt.plot([6,17], y)
plt.show()

enter image description here

目标线是y只要看一下,它应该是-5度左右。 似乎大多数在线解决方案都表明,我们可以通过这样做找到角度

degree = np.math.atan2(y[-1] - y[0], x[-1] - x[0])
degree = np.degrees(degree)

为了简单起见,我省略了y的其他值,只保留了第一个点和最后一个点,所以这里的x[-1] - x[0]部分是11=17-6,这是横穿x轴的y线的长度,这是大多数在线解决方案所建议的,但是所有的方法都没有得到正确的角度,我应该注意到,在我的测试过程中,一些方法似乎为给定的数据单元提供了正确的角度,例如,在另一个数据单元上完全失败,例如

data = [52.3384984,53.04757978,52.04276249,51.77348257,49.93056673,52.24062341,55.74022485,60.77761392,60.89290148,60.1995072,60.40524964,59.00590344,59.67589831,56.49266698,49.02464746,51.53876823,57.77368203,59.48092106,56.63155446,56.0648491 ]
y = [51.337288,50.331895]
plt.plot(data)
plt.plot([3,15], y)
plt.show()

我也尝试了最小化最大化数据,但没有成功,所以考虑到我们有一条直线的第一个和最后一个点以及它的长度,我们如何或者可能以度来确定它的角度


Tags: 数据方法代码importdataplotmatplotlibshow
1条回答
网友
1楼 · 发布于 2024-04-25 09:28:00

有两个角度你需要理解。第一个是基于数据计算的,第二个是基于图形计算的

第一个

您编写的代码正在计算第一个:

degree = np.math.atan2(y[-1] - y[0], x[-1] - x[0])
degree = np.degrees(degree)

delta_y = y[-1] - y[0] = -36.43delta_x = x[-1] - x[0] = 11

degree = -73.20如果你在脑海中画一个三角形,这完全有道理

第二个

然而,你可能会问我,你正在观察一条零下5度的线。这是涉及计算显示比率的第二个问题(注意y轴和x轴的单位长度不同,单位为英寸)。在这里,我找到了一个单独的问题来帮助你计算

from operator import sub
def get_aspect(ax):
    # Total figure size
    figW, figH = ax.get_figure().get_size_inches()
    # Axis size on figure
    _, _, w, h = ax.get_position().bounds
    # Ratio of display units
    disp_ratio = (figH * h) / (figW * w)
    # Ratio of data units
    # Negative over negative because of the order of subtraction
    data_ratio = sub(*ax.get_ylim()) / sub(*ax.get_xlim())

    return disp_ratio / data_ratio

所以你需要乘以这个比率才能得到直线端点的曼哈顿距离

ax = plt.gca()
ratio = get_aspect(ax)
degree = np.math.atan2((y[-1] - y[0])*ratio, x[-1] - x[0])
degree = np.degrees(degree)

结果是-4.760350735146195,约为-5

相关问题 更多 >