线性回归 - 图上的方程式 - Python

Linear regression - equation on the plot - Python

嘿,我想做线性回归并创建一个图,其上也将是我的模型的方程。我有以下代码:

from sklearn.linear_model import LinearRegression

X = np.array((1,2, 3, 4))
Y = np.array((3, 1, 4, 5))

X = X.reshape((-1, 1))
model = LinearRegression().fit(X, Y)


plt.scatter(X, Y, color='g')
plt.plot(X, model.predict(X),color='k')

print(model.coef_[0], model.intercept_)

如何在我的绘图上自动写方程?

Text in Matplotlib Plots

Matplotlib has extensive text support, including support for mathematical expressions, truetype support for raster and vector outputs, newline separated text with arbitrary rotations, and unicode support.

来自official documentation以下命令用于在pyplot界面和面向对象API中创建文本:

pyplot API OO API description
text text Add text at an arbitrary location of the Axes.
annotate annotate Add an annotation, with an optional arrow, at an arbitrary location of the Axes.
xlabel set_xlabel Add a label to the Axes's x-axis.
ylabel set_ylabel Add a label to the Axes's y-axis.
title set_title Add a title to the Axes.
figtext text Add text at an arbitrary location of the Figure.
suptitle suptitle Add a title to the Figure.
from sklearn.linear_model import LinearRegression
import numpy as np
import matplotlib.pyplot as plt

X = np.array((1,2, 3, 4))
Y = np.array((3, 1, 4, 5))

X = X.reshape((-1, 1))
model = LinearRegression().fit(X, Y)

fig = plt.figure()
ax = fig.add_subplot()
plt.scatter(X, Y, color='g')
plt.plot(X, model.predict(X),color='k')
ax.text(1, 4, r'LR equation: $Y = a + bX$', fontsize=10)

print(model.coef_[0], model.intercept_)

剧情: