使用polyfit为matplotlib中创建的趋势线查找正确角度(以度为单位)时出现问题



如果有人能解释/展示如何获得正确的角度读数。。。在我的例子中,角度应该在40-45度之间,但我只显示5.71度或略高于90度(如果我尝试反转x/y(。我已经搜索了一段时间,这让我走到了这一步,但我不知道如何解决这个问题。。我们将不胜感激。提前谢谢。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
x = [1,2,3,4,5,6,7,8,9]
y = [1.1,1.4,1.3,1.6,1.1,1.6,1.7,2.2,1.9]
plt.plot(x,y, marker='o', markersize=1, color="green")
z = np.polyfit(x, y, 1)  
p = np.poly1d(z)
plt.plot(x,p(x),"r--")
degree = np.rad2deg(np.arctan2(y[-1] - y[0], x[-1] - x[0]))
degree2 = np.rad2deg(np.arctan2(x[-1] - x[0], y[-1] - y[0]))
print(degree, degree2)
plt.show()

以防其他人试图弄清楚这一点。方法可以在不打印的情况下找到角度、弧度、坡度和相交。plt.axis('equal'(是正确绘制角度所必需的。。。如果有人知道在不放大的情况下正确显示角度,我希望有更好的方法。

感谢大家的知识和帮助。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
style.use('ggplot')
from statistics import mean
import math
def best_fit_slope_and_intercept(xs,ys):
m = (((mean(xs)*mean(ys)) - mean(xs*ys)) / ((mean(xs)*mean(xs)) - mean(xs*xs)))    
b = mean(ys) - m*mean(xs)    
return m, b
ys = np.asarray([1,2,3,4,5,6,7,8,9])
#ys = np.asarray([1.03,1.035,1.04,1.05,1.06,1.08,1.12,1.09,1.15])
xs = np.arange(len(ys))
m, b = best_fit_slope_and_intercept(xs,ys)
angle_in_radians = math.atan(m)
angle_in_degrees = math.degrees(angle_in_radians)
print("Slope=" + str(m))
print("Intercept=" + str(b))
print("Radians=" + str(angle_in_radians))
print("Degrees=" + str(angle_in_degrees))    
regression_line = []
for x in xs:
regression_line.append((m*x)+b)
plt.scatter(xs,ys,color='#003F72')
plt.plot(xs, regression_line)    
plt.axis('equal')    
plt.show()

最新更新