用Python计算直线(带x坡度)和水平线之间的角度(度)

2024-04-19 18:17:38 发布

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

我需要计算直线和水平线之间的夹角。我的高中数学似乎不及格。

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

slope of best-fit line

我需要水平线和红色虚线之间的夹角。只要看一下,大概应该在30-45度之间。我做错什么了?

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


Tags: importnumpyplotasnplinepltslope
1条回答
网友
1楼 · 发布于 2024-04-19 18:17:38

线路从0到9沿x方向,从7500到9500沿y方向。因此,您的slope在大约30°内仅为0.00788091068301,而不是0.57。你的计算是正确的,但最好使用arctan2:

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

相关问题 更多 >