Weird graph in Linear regression using pyplot

Viewed 917

I am plotting a Linear Regression model using pyplot. Below is my code.

plt.scatter(X_train, y_train, color ='red')
plt.show()

When I plot using the above code, the plot is as shown below: Scatter Plot

I then plotted the line graph using the code below:

plt.plot(X_train, regressor.predict(X_train), color = 'blue')
plt.show()

It shows a line as expected. Line Grpah

But when I try to plot both of them together, the graph is getting messed up as shown below:

plt.scatter(X_train, y_train, color ='red')
plt.plot(X_train, regressor.predict(X_train), color = 'blue')
plt.show()

Linear Regression

Please let me know if I have to do any extra coding to plot a Linear regression graph properly.

1 Answers

Pyplot connects the dots between points in the order of their occurrence in X_train, but there's usually nothing known about the ordering of that. It's rarely sorted. You're going to need to sort your array before plotting it.

sorted_indices = numpy.argsort(X_train)
sorted_X = X_train[sorted_indices]
plt.plot(sorted_X, regressor.predict(sorted_X), color = 'blue')
Related