How to Draw Line of Linear Regression in Python


In this example, we will learn how to draw the line of Linear Regression in Python.

Source Code

import matplotlib.pyplot as plt
from scipy import stats

x = [14.4, 16.5, 11.9, 15.4, 18.6, 22.2, 19.5, 25.3, 23.4, 18.2, 22.6, 17.4]
y = [225, 334, 192, 339, 411, 530, 418, 623, 551, 430, 452, 416]

slope, intercept, r_value, p_value, std_err = stats.linregress(x, y)

# Defines an object that contains linear equations
def myfunc(x):
    return intercept + slope * x

# The value of x on the y-axis
mymodel = list(map(myfunc, x))

plt.scatter(x, y, label='original data')
plt.plot(x, mymodel, 'r', label='fitted line')
plt.legend()
plt.show()

Output:

Subscribe
Notify of
guest
1 Comment
Inline Feedbacks
View all comments
Genio
Genio
5 months ago

Great job!