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

前端 未结 7 1896
轻奢々
轻奢々 2020-11-28 02:18

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

相关标签:
7条回答
  • 2020-11-28 03:13

    You can use this tutorial by Adarsh Menon https://towardsdatascience.com/linear-regression-in-6-lines-of-python-5e1d0cd05b8d

    This way is the easiest I found and it basically looks like:

    import numpy as np
    import matplotlib.pyplot as plt  # To visualize
    import pandas as pd  # To read data
    from sklearn.linear_model import LinearRegression
    data = pd.read_csv('data.csv')  # load data set
    X = data.iloc[:, 0].values.reshape(-1, 1)  # values converts it into a numpy array
    Y = data.iloc[:, 1].values.reshape(-1, 1)  # -1 means that calculate the dimension of rows, but have 1 column
    linear_regressor = LinearRegression()  # create object for the class
    linear_regressor.fit(X, Y)  # perform linear regression
    Y_pred = linear_regressor.predict(X)  # make predictions
    plt.scatter(X, Y)
    plt.plot(X, Y_pred, color='red')
    plt.show()
    
    0 讨论(0)
提交回复
热议问题