Reputation: 21
I have a scatter plot of data and I want to add a best fit line. All I can find online is the statistics package, but my school hasn't paid for that. Is there another was to do this - without the statistics package?
Upvotes: 2
Views: 59840
Reputation: 6586
Use polyfit(x,y,1) to get the coefficients for a linear fit. Use polyval(polyfit(x,y,1),x) to get the fitted y-values for your desired x values. Then you can plot your x and your polvals to form the line.
If you already have a scatter plot, and are only using linear fits, I would do:
// scatterplot above
hold on;
coef_fit = polyfit(x,y,1);
y_fit = polyval(coef_fit,xlim);
plot(xlim,y_fit,'r');
hold off;
Upvotes: 3
Reputation: 13945
You can use polyfit to obtain a 1st order polynomial which best fits your data.
Eg:
Fit = polyfit(x,y,1); % x = x data, y = y data, 1 = order of the polynomial.
You can plot the line along with your scatter plot with polyval:
plot(polyval(Fit,x))
Hope that helps!
Upvotes: 5