How to add error bars to scatter plot?

1,072 次查看(过去 30 天)
Thalya
Thalya 2024-6-18
编辑: dpb 2024-6-19
I have x and y data points that I'm fitting a custom equation to using cftool. I have also calculated vertical error for each of my points. How can I show the error bars and the fit at the same time?

回答(2 个)

Piyush Kumar
Piyush Kumar 2024-6-18
编辑:Piyush Kumar 2024-6-18
If you want to plot errorbars and fit on the same figure, you can follow these steps -
  • Create scatter plot of data points
  • Use "hold on" to keep the plot active to overlay the fit on the same figure
  • Use "errorbar" function to plot data points with vertical error bars
  • Use "plot" function to overlay the fit on the same figure
Adding an example to illustrate -
x = linspace(0, 10, 20);
y = 2*x + 1 + randn(size(x));
errors = 0.5 * ones(size(x));
m = 2;
b = 1;
figure;
scatter(x, y, 'filled', 'DisplayName', 'Data Points');
hold on; % Keep the plot active to overlay the fit
errorbar(x, y, errors, 'o', 'DisplayName', 'Data with Error Bars');
xfit = linspace(min(x), max(x), 100);
yfit = m*xfit + b;
plot(xfit, yfit, '-r', 'DisplayName', 'Linear Fit'); % Overlay the fit with a red line
xlabel('X-axis label');
ylabel('Y-axis label');
legend show; % Display legend
title('Scatter Plot with Error Bars and Linear Fit');
hold off
Please replace the variables used with the actual data.

dpb
dpb 2024-6-18
编辑:dpb 2024-6-19
We don't have your results nor equation; export it to a curve fit object from the interactive tool...then use it similarly as
% get a sample dataset from errorbar() example...
x = [1:10:100].';
y = [20 30 45 40 60 65 80 75 95 90].';
err = [5 8 2 9 3 3 8 3 9 3];
cf=fit(x,y,'poly3','normalize','on'); % fit a poly; use your saved model instead
% begin actual plotting here...
hL=plot(cf,x,y); % start with the curvefit object line
hold on % we want to add errorbar on top...
hEB=errorbar(x,y,err,'.b'); % add errorbar() w/o a linestyle in the triplet is same as scatter()
hL=legend([hEB,hL(2)],'Data with Error','Fitted Model','Location','Northwest');
The above picks the data points from the errorbar and the fitted curve from the fit object to put on the legend. In this order and with the "." for the marker, the data points from the fit object aren't visible and the legend matches the errorbar style instead of the data points only.
As noted, save and use your fitted model in lieu of the created one here...and salt to suit the details like labels, colors, linestyles, etc., etc., ...

类别

Help CenterFile Exchange 中查找有关 Errorbars 的更多信息

标签

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by