2016-03-06 511 views
3

我需要計算線和水平線之間的角度。我的高中數學似乎讓我失望。計算線(斜率x)和水平線之間的角度(度)

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,但都沒有成功。

+0

您已經忘記計算圖表的比例。 – jtbandes

+0

另外,請使用[arctan2](http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.arctan2.html)! – jtbandes

+0

hi jtbandes,我如何解釋我的圖表的規模? – ljc

回答

9

該行沿x方向從0到9,y方向從7500到9500.因此,您的slope僅爲0.00788091068301,而不是約30°時爲0.57。您的計算是正確的,但更好地使用arctan2:

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