How do you draw a line of best fit on a scatter plot in python?


First, we can create a scatter for different data points using the scatter method, and then, we can plot the lines using the plot method.

Steps

  • Create a new figure, or activate an existing figure with figure size(4, 3), using figure() method.

  • Add an axis to the current figure and make it the current axes, create x using plt.axes().

  • Draw scatter points using scatter() method.

  • Draw line using ax.plot() method.

  • Set the X-axis label using plt.xlabel() method.

  • Set the Y-axis label using plt.ylabel() method.

  • To show the plot, use plt.show() method.

Example

import random
import matplotlib.pyplot as plt

plt.figure(figsize=(4, 3))
ax = plt.axes()
ax.scatter([random.randint(1, 1000) % 50 for i in range(100)],
[random.randint(1, 1000) % 50 for i in range(100)])
ax.plot([1, 2, 4, 50], [1, 2, 4, 50])

ax.set_xlabel('x')
ax.set_ylabel('y')

plt.show()

Output

How do you draw a line of best fit on a scatter plot in python?

How do you draw a line of best fit on a scatter plot in python?

Updated on 17-Mar-2021 08:48:17

  • Related Questions & Answers
  • Adding a line to a scatter plot using Python's Matplotlib
  • How to draw an average line for a scatter plot in MatPlotLib?
  • How to make a 3D scatter plot in Python?
  • How to plot additional points on the top of a scatter plot in Matplotlib?
  • How to make a scatter plot for clustering in Python?
  • How to animate a scatter plot in Matplotlib?
  • Connecting two points on a 3D scatter plot in Python and Matplotlib
  • Plot a multicolored line based on a condition in Python Matplotlib
  • Python - Draw a Scatter Plot for a Pandas DataFrame
  • How to plot scatter masked points and add a line demarking masked regions in Matplotlib?
  • How to plot a dashed line on a Seaborn lineplot in Matplotlib?
  • How do you plot a vertical line on a time series plot in Pandas?
  • Controlling the alpha value on a 3D scatter plot using Python and Matplotlib
  • Create a Scatter Plot with SeaBorn – Python Pandas
  • How can Seaborn library be used to display a Scatter Plot in Python?


Regression - How to program the Best Fit Line

Welcome to the 9th part of our machine learning regression tutorial within our Machine Learning with Python tutorial series. We've been working on calculating the regression, or best-fit, line for a given dataset in Python. Previously, we wrote a function that will gather the slope, and now we need to calculate the y-intercept. Our code up to this point:

from statistics import mean
import numpy as np

xs = np.array([1,2,3,4,5], dtype=np.float64)
ys = np.array([5,4,6,5,6], dtype=np.float64)

def best_fit_slope(xs,ys):
    m = (((mean(xs)*mean(ys)) - mean(xs*ys)) /
         ((mean(xs)*mean(xs)) - mean(xs*xs)))
    return m

m = best_fit_slope(xs,ys)
print(m)

As a reminder, the calculation for the best-fit line's y-intercept is:

How do you draw a line of best fit on a scatter plot in python?

This one will be a bit easier than the slope was. We can save a few lines by incorporating this into our other function. We'll rename it to best_fit_slope_and_intercept.

Next, we can fill in: b = mean(ys) - (m*mean(xs)), and return m and b:

def best_fit_slope_and_intercept(xs,ys):
    m = (((mean(xs)*mean(ys)) - mean(xs*ys)) /
         ((mean(xs)*mean(xs)) - mean(xs*xs)))
    
    b = mean(ys) - m*mean(xs)
    
    return m, b

Now we can call upon it with: m, b = best_fit_slope_and_intercept(xs,ys)

Our full code up to this point:

from statistics import mean
import numpy as np

xs = np.array([1,2,3,4,5], dtype=np.float64)
ys = np.array([5,4,6,5,6], dtype=np.float64)

def best_fit_slope_and_intercept(xs,ys):
    m = (((mean(xs)*mean(ys)) - mean(xs*ys)) /
         ((mean(xs)*mean(xs)) - mean(xs*xs)))
    
    b = mean(ys) - m*mean(xs)
    
    return m, b

m, b = best_fit_slope_and_intercept(xs,ys)

print(m,b)

Output should be: 0.3 4.3

Now we just need to create a line for the data:

How do you draw a line of best fit on a scatter plot in python?

Recall that y=mx+b. We could make a function for this... or just knock it out in a single 1-liner for loop:

regression_line = [(m*x)+b for x in xs]

The above 1-liner for loop is the same as doing:

regression_line = []
for x in xs:
    regression_line.append((m*x)+b)

Great, let's reap the fruits of our labor finally! Add the following imports:

import matplotlib.pyplot as plt
from matplotlib import style
style.use('ggplot')

This will allow us to make graphs, and make them not so ugly. Now at the end:

plt.scatter(xs,ys,color='#003F72')
plt.plot(xs, regression_line)
plt.show()

First we plot a scatter plot of the existing data, then we graph our regression line, then finally show it. If you're not familiar with , you can check out the Data Visualization with Python and Matplotlib tutorial series.

Output:

How do you draw a line of best fit on a scatter plot in python?

Congratulations for making it this far! So, how might you go about actually making a prediction based on this model you just made? Simple enough, right? You have your model, you just fill in x. For example, let's predict out a couple of points:

predict_x = 7

We have our input data, our "feature" so to speak. What's the label?

predict_y = (m*predict_x)+b
print(predict_y)

Output: 6.4

We can even graph it:

predict_x = 7
predict_y = (m*predict_x)+b

plt.scatter(xs,ys,color='#003F72',label='data')
plt.plot(xs, regression_line, label='regression line')
plt.legend(loc=4)
plt.show()

Output:

How do you draw a line of best fit on a scatter plot in python?

We now know how to create our own models, which is great, but we're stilling missing something integral: how accurate is our model? This is the topic for discussion in the next tutorial!

The next tutorial:


How do you add a line of best fit on a scatter plot in Python?

How to plot a line of best fit in Python.
x = np. array([1, 3, 5, 7]).
y = np. array([ 6, 3, 9, 5 ]).
m, b = np. polyfit(x, y, 1) m = slope, b = intercept..
plt. plot(x, y, 'o') create scatter plot..
plt. plot(x, m*x + b) add line of best fit..

How do you draw a line on a scatter plot in Python?

Create a new figure, or activate an existing figure with figure size(4, 3), using figure() method..
Add an axis to the current figure and make it the current axes, create x using plt. ... .
Draw scatter points using scatter() method..
Draw line using ax. ... .
Set the X-axis label using plt. ... .
Set the Y-axis label using plt..

Can we draw trendline in scatter plot Python?

MatPlotLib with Python To draw a scatter trend line using matplotlib, we can use polyfit() and poly1d() methods to get the trend line points.