2

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?

Tim
  • 2,563
  • 1
  • 23
  • 31
user2998603
  • 21
  • 1
  • 1
  • 3

2 Answers2

5

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!

Benoit_11
  • 13,905
  • 2
  • 24
  • 35
2

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;
user3685285
  • 6,066
  • 13
  • 54
  • 95