How do i plot one best fit line for multiple data sets?
17 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(2 个)
Star Strider
2021-12-30
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 个评论
Image Analyst
2021-12-30
编辑:Image Analyst
2021-12-30
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Get Started with Curve Fitting Toolbox 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!