MATLAB: Error bars on grouped bar plot

bar plotserror

Hi, I would like to place error bars for the following grouped bar plot. I tired different solution on the web but couldn't find the one that worked… Any help would be appreciated! Thanks

Best Answer

You didn’t say what you tried or what version of MATLAB you’re running.
This will work for R2014b and later:
a=[0,1,0,0;
4,3,2,1;
2,2,1,3;
1,0,0,0];
b=[0,1,0,0;
1,2,1,1;
1,1,1,2;
1,0,0,0];
ctrs = 1:4;
data = a;
figure(1)
hBar = bar(ctrs, data);
for k1 = 1:size(a,1)
ctr(k1,:) = bsxfun(@plus, hBar(1).XData, [hBar(k1).XOffset]');
ydt(k1,:) = hBar(k1).YData;
end
hold on
errorbar(ctr, ydt, b, '.r')
hold off
Here, ‘a’ are the bars, and ‘b’ are the error bars.
A different approach is necessary for R2014a and earlier:
figure(1)
hBar = bar(xval,data); % Plot Data, Get Handle
set(hBar(1), 'FaceColor', cmap(2,:)) % Colour First Bar Set

set(hBar(2), 'FaceColor', cmap(3,:)) % Colour First Bar Set
set(gca, 'YLim', [870 1080]) % Set Y-Axis Limits
hold on
for k1 = 1:length(hBar) % Loop: Plots Error Bars
hb = get(get(hBar(k1),'Children'), 'XData');
midbar = mean(hb);
errorbar(midbar, data(:,k1), errs(:,k1), '.') % plotting errors
sigbarx(k1,:) = midbar; % Use To Plot Significance Bars
end
I can no longer run the R2014a code, so you will have to experiment with the concepts with your data.
In both code examples, the errorbar plotting occurs in the for loop.