How do i plot one best fit line for multiple data sets?
22 views (last 30 days)
Show older comments
I am trying to plot 3 sets of data on the same set of axes, and then plot one line of best fit through all the data sets.
I can display all the data on the same axis with no issues simply using plot, see image below

However, when i try to plot a line of best fit through this data, it only allows me to plot it for one data set at a time, see below.

This is not what i want to do, as each line only accounts for one data set rather than every data point on the graph. Does anyone know how i could fix this?
Thank you!
0 Comments
Answers (2)
Star Strider
on 30 Dec 2021
I would do something like this —
x1 = 0:0.5:10;
x2 = x1 + 2;
x3 = x1 - 0.5;
y1 = 1 + 0.2*x1 + randn(size(x1))*0.2;
y2 = 1.5 + 0.1*x2 + randn(size(x2))*0.1;
y3 = 0.5 + 0.3*x3 + randn(size(x3))*0.3;
DM = [x1, x2, x3;
ones(size([x1, x2, x3]))].';
B = DM \ [y1, y2, y3].'
LBF = DM * B;
figure
plot(x1, y1, '.')
hold on
plot(x2, y2, '.')
plot(x3, y3, '.')
plot(DM(:,1), LBF, '-r')
hold off
legend('y_1','y_2','y_3','Line of Best Fit', 'Location','best')
text(1, 3, sprintf('y = %.3f\\cdotx%+.3f',B))
The strategy here is to concatenate the independent variable vectors and the dependent variable vectors separately, then use them as ordinary independent and dependent variable vectors in the regression (linear here for simplicity). The independent variable vectors can be different values and different lengths (although the same lengths here) making this approach reasonably robust.
A nonlinear approach would proceed similarly, however if different parameters were to be estimated for different independnet and dependent variable vectors, all the sizes would have to be the same for all the vectors, requiring a different approach.
.
0 Comments
Image Analyst
on 30 Dec 2021
Edited: Image Analyst
on 30 Dec 2021
Not sure of your definition of best, but how about just taking the average
plot(x, data1, '-', 'LineWidth', 1);
hold on;
plot(x, data2, '-', 'LineWidth', 1);
plot(x, data3, '-', 'LineWidth', 1);
allData = (data1 + data2 + data3) / 3;
% allData may wiggle around a bit just like the actual data.
plot(x, allData, 'r-', 'LineWidth', 3);
% If you don't want the average data but want a line instead, then
% fit data to a line.
xTrain = [x(:); x(:), x(:)];
yTrain = allData(:);
lineCoefficients = polyfit(xTrain, yTrain, 1);
% Get a vector of line fit points for every x location
yFitted = polyval(coefficients, x);
plot(x, yFitted, 'm-', 'LineWidth', 2);
If you want to interpolate additional points in between your existing x points, you could certainly do that. See my attached spline interpolation demo.
0 Comments
See Also
Categories
Find more on Get Started with Curve Fitting Toolbox in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!