user40465
user40465

Reputation: 421

Best fit line for a degree 2 polynomial regression

I'm trying to create the best fit line between 2 points x and y using the polyfit function in numpy with degree 2.

fit = polyfit(x, y, 2)
fit_fn = poly1d(fit)

plot(x, y, 'k.', x, fit_fn(x), '--r', linewidth=1)
plt.xlabel("x")
plt.ylabel("y")

I'm bit confused why is the best fit line so thick instead of being a simple line. Do you thing I'm doing something wrong in the code?

fit with fat line

Upvotes: 3

Views: 1180

Answers (1)

sheridp
sheridp

Reputation: 1396

The problem is that your x is not sorted. Try

plot(x, y, 'k.', sort(x), fit_fn(sort(x)), '--r', linewidth=1)

plot "connects the dots" from (x_0, fit_fn(x_0)) to (x_1, fit_fn(x_1)). If your x's aren't sorted, then the line is zig-zagging all over the place, making it look thick.

Upvotes: 7

Related Questions