Home » Python » python – Cant seem to draw linear regression in the same graph as scatterplot-Exceptionshub

python – Cant seem to draw linear regression in the same graph as scatterplot-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I have been trying to plot a linear regression line on my scatterplot but the graphs seem to push my scatterplot down. The scatterplot seem fine without the regression line. Please see image 1.

But once i run ax.plot(X,Y_pred,color= 'red') the graph gets distorted. I have checked the values they all seem fine. Im just confused why this happens. Please help thank you.

Image 1enter image description here

Image 2 – With regression line
enter image description here

    #for regression line
X = latest_data1.iloc[:,3].values.reshape(-1,1)
Y= latest_data1.iloc[:,4].values.reshape(-1,1)
linear_regressor = LinearRegression()  # create object for the class
linear_regressor.fit(X,Y)
Y_pred = linear_regressor.predict(X)



fig, ax = plt.subplots()
ax.scatter(latest_data1['residential_land_area'],latest_data1['dwelling_units_under_management'])
ax.plot(X,Y_pred,color= 'red')
plt.title("Number of units vs Residential Land area in 2018 (Density)", fontsize=18, y=1.03)
plt.xlabel('Residential land area (hectares)')
plt.ylabel('Dwelling units')
ax.legend()
plt.show()
How to&Answers: