close

how to add regression line and regression line equation on graph

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about how to add regression line and regression line equation on graph in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

how to add regression line and regression line equation on graph?

  1. how to add regression line and regression line equation on graph?

    You cannot multiply a list with a float number. So you may create a numpy array from the input list x

  2. add regression line and regression line equation on graph

    You cannot multiply a list with a float number. So you may create a numpy array from the input list x

Method 1

You cannot multiply a list with a float number. So you may create a numpy array from the input list x,

line = slope*np.array(x)+intercept

More ideally you would read in your data using np.genfromtxt,

x,y = np.genfromtxt("input.txt", unpack=True) 

Complete example:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
from matplotlib.ticker import MaxNLocator
from scipy import stats

x,y = np.genfromtxt("input.txt", unpack=True) 

fig = plt.figure(figsize=(2.2,2.2), dpi=300)
ax = plt.subplot(111)

plt.xlim(4, -8)
plt.ylim(4, -8)

ax.xaxis.set_major_locator(MaxNLocator(6))
ax.yaxis.set_major_locator(MaxNLocator(6))

ax.xaxis.set_minor_locator(MultipleLocator(1))
ax.yaxis.set_minor_locator(MultipleLocator(1))


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

line = slope*x+intercept
plt.plot(x, line, 'r', label='y={:.2f}x+{:.2f}'.format(slope,intercept))
#end

plt.scatter(x,y, color="k", s=3.5)
plt.legend(fontsize=9)

plt.show()
enter image description here

Method 2

You could try and add this piece of code for the regression line:

# To plot the regression line
plt.plot(X, (B0 + B1*x), label = 'y = {:.2f} + {:.2f}*x'.format(B0, B1))
plt.legend(loc='lower right')

Here is a screenshot of the visualization for the Linear Regression code I had written:

enter image description here

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read