How to plot a line of best fit in Python

Plotting a line of best fit plots the line derived from perfroming Ordinary Least Squares (OLS) regression on a dataset.

Solution for How to plot a line of best fit in Python : You can use numpy.polyfit() and matplotlib.pyplot.plot() to plot a line of best fit Call numpy.polyfit(x, y, deg) with x and y as arrays of x and y-values and deg as 1 to calculate the slope and y-intercept of the line of best fit. Plot the line by calling matplotlib.pyplot.plot(x, eq) with eq as the y-intercept added to the product of the slope and x.


how-to-plot-a-line-of-best-fit-in-python