Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate angle (degrees) in Python between line (with slope x) and horizontal

I need to calculate the angle between a line and the horizontal. My high school maths seems to be failing me.

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()

The results are as follow:

slope: 0.00788091068301
angle: 0.00788074753125

slope of best-fit line

I need the angle between the horizontal and the red dotted line. Just by looking at it, it should probably be something between 30-45 degrees. What am I doing wrong?

* regarding slope = (y[-1] - y[0]) / (x[-1] - x[0]), I have also tried numpy.diff and scipy.stats.linregress, but no success either.

like image 229
ljc Avatar asked Mar 06 '16 09:03

ljc


People also ask

How do you find the degree of an angle in Python?

The angle is calculated by the formula tan-1(x/y). Parameters : z : [array_like] A complex number or sequence of complex numbers. deg : [bool, optional] Return angle in degrees if True, radians if False (default).

How do you go from gradient to angle?

How to Convert Gradians to Degrees. To convert a gradian measurement to a degree measurement, multiply the angle by the conversion ratio. The angle in degrees is equal to the gradians multiplied by 0.9.


1 Answers

The line goes in x-direction from 0 to 9 and in y-direction from 7500 to 9500. Therefore your slope is only 0.00788091068301 and not 0.57 for about 30°. Your calculations are correct, but better use arctan2:

angle = np.rad2deg(np.arctan2(y[-1] - y[0], x[-1] - x[0]))
like image 78
Daniel Avatar answered Oct 04 '22 17:10

Daniel