How to add error bars as a region about the data?
4 views (last 30 days)
Show older comments
I have a plot with a lot of data points plotted using the loglog function. How do I add error bars as a light-shaded zone around the data? Something like what you see in the following, though not necessarily quite the same aesthetics.
dpb on 16 Jan 2023
Edited: dpb on 16 Jan 2023
Very crude but with some data at hand illustrates one way...
hL=plot(X,c,'kx-'); % plot original data normal line with 'x' marker
[b,S]=polyfit(X,log10(c),1); % do a semilog fit to an existing dataset from earlier answer
[yhat,se]=polyval(b,X,S); % the predicted value and error -- in log10
yhat=10.^yhat; % convert the predicted to actual values
hL(2)=plot(X,yhat,'k-','linewidth',2); % add the fit response -- heavy black line no markers
yhi=yhat+10.^(1.96*se); % the upper 95% observation bounds
ylo=yhat-10.^se/4; % scale down the lower to keep positive for demo only
hF=fill([X flip(X)],[ylo flip(yhi)],'m','FaceAlpha',0.5); % the magic -- fill between ylo, yhi
The above produced the following figure...
You can obviously choose a less garish color than magenta, but the 'FaceAlpha' setting at less than 0.5 or so is the key to being able to write on top of the existing lines and still see them through the colored area. fill uses an x, y vector to define the region; note the "trick" of string the X vector back-to-back, flipping the second copy to retrace from end of first back to beginning and then putting the two error vectors together to match.
You'll note a small white gap at the left edge; that's because the X data begin at 1 and the autoscaled axes limits go to zero; you can augment X by the zero first for the fill() if desired to make that artifact disappear.
Anyways, there's a set of breadcrumbs through the forest; if you are on loglog scale then will have to deal with that as well as for the semilogy illustrated here; I forget if there's a builtin loglog regression model or not in either the statistics or curve fitting toolbox that actually does the whole thing for you or not...
More Answers (0)
Find more on Annotations 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!