Scatter Plot with Linear Fit using Matplotlib

  • Share this:

Code introduction


This function uses the matplotlib library to plot a scatter plot of the data and fits a linear model to it, displaying the regression line.


Technology Stack : matplotlib, numpy

Code Type : Function

Code Difficulty : Intermediate


                
                    
import numpy as np
import matplotlib.pyplot as plt

def plot_scatter_with_fit(x, y):
    # Plot a scatter plot of the data
    plt.scatter(x, y, color='blue')
    
    # Fit a linear model to the data and plot the regression line
    z = np.polyfit(x, y, 1)
    p = np.poly1d(z)
    plt.plot(x, p(x), "r--")
    
    # Show the plot
    plt.show()

# Example usage:
# x = np.random.rand(10)
# y = 2 * x + np.random.randn(10) * 0.5
# plot_scatter_with_fit(x, y)