【问题标题】:Calculate angle (degrees) in Python between line (with slope x) and horizontal在 Python 中计算直线(斜率为 x)和水平之间的角度(度数)
【发布时间】:2016-06-19 22:07:35
【问题描述】:

我需要计算一条线与水平线之间的角度。我的高中数学似乎不及格。

import matplotlib.pyplot as plt
import numpy as np

x = [8450.0, 8061.0, 7524.0, 7180.0, 8247.0, 8929.0, 8896.0, 9736.0, 9658.0, 9592.0]
y = range(len(x))

best_fit_line = np.poly1d(np.polyfit(y, x, 1))(y)

slope = (y[-1] - y[0]) / (x[-1] - x[0])
angle = np.arctan(slope)

print 'slope: ' + str(slope)
print 'angle: ' + str(angle)

plt.figure(figsize=(8,6))
plt.plot(x)
plt.plot(best_fit_line, '--', color='r')
plt.show()

结果如下:

slope: 0.00788091068301
angle: 0.00788074753125

我需要水平线和红色虚线之间的角度。光看它,它可能应该在 30-45 度之间。我做错了什么?

* 关于slope = (y[-1] - y[0]) / (x[-1] - x[0]),我也尝试过numpy.diffscipy.stats.linregress,但也没有成功。

【问题讨论】:

  • 您忘记考虑图表的比例。
  • 另外,请使用arctan2
  • 嗨 jtbandes,我如何计算图表的比例?

标签: python numpy math time-series angle


【解决方案1】:

这条线在 x 方向上从 0 到 9,在 y 方向上从 7500 到 9500。因此,您的 slope 只有 0.00788091068301 而不是 0.57 约 30°。您的计算是正确的,但最好使用 arctan2:

angle = np.rad2deg(np.arctan2(y[-1] - y[0], x[-1] - x[0]))

【讨论】:

    猜你喜欢
    • 2011-02-10
    • 2011-11-27
    • 1970-01-01
    • 2011-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-17
    • 2017-07-23
    相关资源
    最近更新 更多