Calculate angle (degrees) in Python between line (with slope x) and horizontal
20,267
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]))
Author by
ljc
Updated on July 09, 2022Comments
-
ljc almost 2 years
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
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 triednumpy.diff
andscipy.stats.linregress
, but no success either.