help with plotting with error bars with fit
8 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
hello,
i can not succed to do a simple thing
1.do a fit of some values x, y
2.have the error bars
3.plot tougether the fit with the corresponding error bars
i am getting the plot where the error bars are connected by a line so i get two lines with error bars (the line from the fit and the line from the error line)
figure
hold on
Fit_1=fit(X,Y,'poly2');
plot(Fit_1,X,Y);
hE_1=errorbar(X, Y, err_1);
i am getting something like this:

also any easy way to add the correct legend? as i would like to note only the error bars and the fitted curve with the same color and name it in the legend (in total there are 9 polynoms and the 9 corresponding error bars..)
0 comentarios
Respuestas (1)
Rahul
el 14 de Jul. de 2025
Hi franco,
I understand you're trying to fit some '(x, y)' data in MATLAB, add error bars, and plot both the fitted curve and the corresponding error bars together in a clear way. Based on the description and the plot, the issue could be caused by 'plot(Fit_1, X, Y)' command, which plots both the fitted curve and connects the data points, thus creating the appearance of two overlapping lines with error bars.
To achieve a clean plot where the error bars are shown only on the data points and the fitted curve is displayed separately, you can structure your code as follows:
% Example data
X = [0, 0.003, 0.006, 0.01];
Y = [0, 13, 30, 60];
err_1 = [0.5, 1.5, 2, 2.5];
% Fit polynomial
Fit_1 = fit(X.', Y.', 'poly2');
% Generate smooth curve for fit
x_fit = linspace(min(X), max(X), 200);
y_fit = feval(Fit_1, x_fit);
% Plot
figure; hold on;
errorbar(X, Y, err_1, 'o', 'Color', 'b', 'DisplayName', 'Data with error bars');
plot(x_fit, y_fit, 'r-', 'LineWidth', 1.5, 'DisplayName', 'Fitted curve');
legend('show');
xlabel('x'); ylabel('y');
title('Polynomial Fit with Error Bars');
grid on;
This approach separates the two procedures as follows: 'errorbar' handles the original data points with vertical error bars (without connecting lines), and 'plot' draws a smooth curve for the fitted polynomial. The use of the 'DisplayName' property helps manage the legend entries clearly and ensures only the desired elements appear in the legend.
In case you want to plot multiple datasets, for e.g., the 9 polynomials and their corresponding error bars, you can wrap this structure in a loop and use a colormap (like 'lines(9)') to assign unique colors to each curve and its matching error bars.
For more information regarding the usage of the 'plot' function in MATLAB, you can refer to the following documentation link:
Hope this helps!
0 comentarios
Ver también
Categorías
Más información sobre Legend en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!