1

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?

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

The case is that I want to print Y = model.coef_[0] x + model.intercept_ instead of Y = a + bX and I want to do it automatically and dont write it by hand
You could try something like ax.text(1, 4, f'$Y = {model.coef_[0]} * x + {model.intercept_}$', fontsize=10). Round ax.text(1, 4, f'$Y = {round(model.coef_[0], 2)} * x + {model.intercept_}$', fontsize=10)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.