Johhn White
Johhn White

Reputation: 59

Linear regression - equation on the plot - Python

Hey I want to do linear regression and create a plot on which will be also equation of my model. I have following code:

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_)

How to write equation on my plot automatically?

Upvotes: 1

Views: 3830

Answers (1)

Ailurophile
Ailurophile

Reputation: 3005

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.

From the official documentation the following commands are used to create text in the pyplot interface and the object-oriented 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_)

Plot:

enter image description here

Upvotes: 2

Related Questions