Search code examples
pythonnumpymatplotliblinear-regressionscatter-plot

How to overplot a line on a scatter plot in python?


I have two vectors of data and I've put them into pyplot.scatter(). Now I'd like to over plot a linear fit to these data. How would I do this? I've tried using scikitlearn and np.polyfit().


Solution

  • import numpy as np
    from numpy.polynomial.polynomial import polyfit
    import matplotlib.pyplot as plt
    
    # Sample data
    x = np.arange(10)
    y = 5 * x + 10
    
    # Fit with polyfit
    b, m = polyfit(x, y, 1)
    
    plt.plot(x, y, '.')
    plt.plot(x, b + m * x, '-')
    plt.show()
    

    enter image description here