使用 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.7,2.2,1.9]

plt.plot(x,y,marker='o',markersize=1,color="green")
z = np.polyfit(x,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()

解决方法

5.71 度是正确的。角度看起来更大的原因是轴缩放。如果我们等比例缩放轴,我们可以看到可视化的真实角度:

...
plt.axis('equal')
plt.show()

equal axis

要放大,请将 xlim()ylim() 设置为您想要的范围:

...
plt.axis("equal")
plt.xlim(1,1.3)
plt.ylim(1,1.3)
plt.show()

zoomed with xlim/ylim

,

以防其他人试图解决这个问题。方法无需绘图即可求角度、弧度、斜率和相交。 需要 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()