python-最小二乘法拟合直线

拟合直线

model = np.polyfit(df_flat['code'], df_flat['data'], 1)
predict = np.poly1d(model)
x_lin_reg = range(df_flat.at[0, 'code'] - 800, df_flat.at[len(df_flat) - 1, 'code'] + 800)
y_lin_reg = predict(x_lin_reg)
plt.plot(x_lin_reg, y_lin_reg, c='r')

两直线交点

def lineEquation(x1, y1, x2, y2):
# 一般式 Ax+By+C=0
A = y2 - y1
B = x1 - x2
C = x2 * y1 - x1 * y2
return A, B, C

def intersectPoint(x1, y1, x2, y2, x3, y3, x4, y4):
# from http://www.cnblogs.com/DHUtoBUAA/
A1, B1, C1 = lineEquation(x1, y1, x2, y2)
A2, B2, C2 = lineEquation(x3, y3, x4, y4)
m = A1 * B2 - A2 * B1
if m == 0:
print("无交点")
else:
x = (C2 * B1 - C1 * B2) / m
y = (C1 * A2 - C2 * A1) / m
return x, y

# 计算两直线的交叉点 intersectPoint(x1,y1,x2,y2,x3,y3,x4,y4)
xi, yi = intersectPoint(lines[0][0], lines[0][1], lines[0][2], lines[0][3], lines[1][0], lines[1][1], lines[1][2], lines[1][3])
self.ax.scatter(xi, yi, color='blue')
20200921_160001.png
x1, y1 = 1.0, 2.0 # slope & intercept (line 1)
x2, y2 = 4.0, -3.0 # slope & intercept (line 2)

x = np.linspace(-10,10,500)

xi = (y1 - y2) / (x2 - x1)
yi = x1 * xi + y1

print('(xi,yi)',xi,yi)
plt.scatter(xi,yi, color='black' )

获取直线交叉点角度

def GetCrossAngle(p1, p2):
"""
获取两直线交叉点的角度
:param p1:
:param p2:
:return:
"""
arr_0 = np.array([(p2.x - p1.x), (p2.y - p1.y)])
arr_1 = np.array([(p2.x - p1.x), (p2.y - p1.y)])
cos_value = (float(arr_0.dot(arr_1)) / (np.sqrt(arr_0.dot(arr_0)) * np.sqrt(arr_1.dot(arr_1)))) # 注意转成浮点数运算

return np.arccos(cos_value) * (180 / np.pi)