3

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.

0

1 Answer 1

2

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')
Sign up to request clarification or add additional context in comments.

1 Comment

Admittedly your case does look pretty weird, but it may be some quirk of matplotlib. I'm not sure this is going to help.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.