Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Line of best fit scatter plot

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.

like image 433
Jon Avatar asked Jan 08 '10 01:01

Jon


People also ask

How do you find lines of best fit?

A line of best fit can be roughly determined using an eyeball method by drawing a straight line on a scatter plot so that the number of points above the line and below the line is about equal (and the line passes through as many points as possible).

What is the difference between a scatter plot and a line of best fit?

A scatter plot is a graph in which ordered pairs of data are plotted. You can use a scatter plot to determine if a relationship, or an association exists between two sets of data. This is also known as a correlation. A line of best fit is a straight line that best represents the data on a scatter plot.

What does the best fit line tell you?

The line of best fit (or trendline) is an educated guess about where a linear equation might fall in a set of data plotted on a scatter plot.


1 Answers

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);
like image 169
Mark Elliot Avatar answered Oct 02 '22 16:10

Mark Elliot