Search code examples
pythonmatplotlibplotjupyter-notebooklinear-regression

My scatter plot with a linear regression line is not showing


I've been trying to graph a scatter plot with a linear regression line in a jupyter notebook, however my final plot is not showing up.

%matplotlib inline
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression

linear_regressor = LinearRegression()

X = fish_df.iloc[:,2].values.reshape(-1,1)
Y = fish_df.iloc[:,4].values.reshape(-1,1)

linear_regressor.fit(X, Y)
Y_pred = linear_regressor.predict(X)

plt.scatter(X,Y, color="green")

plt.plot(X, Y_pred, color="red")
plt.show()

at first I was having trouble showing any plot but then I added %matplotlib inline then I managed to get the scatter plot and the line for my linear regression, however I wanted to get a scatterplot with the linear regression line. Is there another way to plot this or am I missing certain code ?

scatter plot
linear regression line


Solution

  • When I repeat your experiment, it works for me.

    I replaced your data lines with:

    import numpy as np
    from random import random
    X = np.arange(10).reshape(-1, 1)
    y = np.arange(10).reshape(-1, 1) + np.random.rand(10).reshape(-1, 1)
    

    I then ran your code in jupyter-notebook and produced a plot with both the regression line and scatter plot on one graph. I would suggest checking your data and/or restarting jupyter-notebook. Or, it could be a particular version that is the problem.

    Plot