Line of best fit scatter plot

Jon picture Jon · Jan 8, 2010 · Viewed 92.2k times · Source

I'm trying to do a scatter plot with a line of best fit in matlab, I can get a scatter plot using either scatter(x1,x2) or scatterplot(x1,x2) but the basic fitting option is shadowed out and lsline returns the error 'No allowed line types found. Nothing done'

Any help would be great,

Thanks, Jon.

Answer

Mark Elliot picture Mark Elliot · Jan 8, 2010

lsline is only available in the Statistics Toolbox, do you have the statistics toolbox? A more general solution might be to use polyfit.

You need to use polyfit to fit a line to your data. Suppose you have some data in y and you have corresponding domain values in x, (ie you have data approximating y = f(x) for arbitrary f) then you can fit a linear curve as follows:

p = polyfit(x,y,1);   % p returns 2 coefficients fitting r = a_1 * x + a_2
r = p(1) .* x + p(2); % compute a new vector r that has matching datapoints in x

% now plot both the points in y and the curve fit in r
plot(x, y, 'x');
hold on;
plot(x, r, '-');
hold off;

Note that if you want to fit an arbitrary polynomial to your data you can do so by changing the last parameter of polyfit to be the dimensionality of the curvefit. Suppose we call this dimension d, you'll receive back d+1 coefficients in p, which represent a polynomial conforming to an estimate of f(x):

f(x) = p(1) * x^d + p(2) * x^(d-1) + ... + p(d)*x + p(d+1)

Edit, as noted in a comment you can also use polyval to compute r, its syntax would like like this:

r = polyval(p, x);