- 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
How to add error bars to scatter plot?
129 views (last 30 days)
Show older comments
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?
0 Comments
Answers (2)
Piyush Kumar
on 18 Jun 2024
Edited: Piyush Kumar
on 18 Jun 2024
If you want to plot errorbars and fit on the same figure, you can follow these steps -
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.
0 Comments
dpb
on 18 Jun 2024
Edited: dpb
on 19 Jun 2024
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., ...
0 Comments
See Also
Categories
Find more on Errorbars in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!