Place errorbars on a grouped bar graph in MATLAB

Well, although MATLAB is not great for plotting, a few tricks can make it drawing easier.

We often use errorbar function to plot errorbar but it’s impossible for Matlab to put error bars on a grouped bar graph. Matlab simply gives a shit if you command it straightforwardly. For example:

The error bars are located in the center of each grouped bars, rather than the individual bar in each grouped bars.

Here is the note I made, the main code is from the link below:

Code example:

``````Data set:

mm: 4 by 6 matrix; ci: 4 by 6 matrix

mm =

[0.2081 0.3440 0.3470 0.7018 0.8422 0.9874
0.2628 0.3043 0.4032 0.7287 0.8462 1.1055
0.2928 0.3139 0.4176 0.7241 0.8319 1.0483
0.2287 0.2538 0.3665 0.4895 0.8999 1.1309]

ci =

[0.0176 0.0473 0.0443 0.0724 0.0855 0.0931
0.0312 0.0201 0.0407 0.0621 0.0604 0.0874
0.0291 0.0330 0.0403 0.0756 0.0732 0.0847
0.0228 0.0150 0.0264 0.0598 0.0922 0.0861]``````
``````figure;
h = bar(mm');
set(h,'BarWidth',0.8);    % The bars will now touch each other
set(gca,'fontsize', 18);
set(get(gca,'YLabel'),'String','RT in Seconds')
lh = legend('Valid Left', 'Invalid left', 'Valid right', 'Invalid right');
set(lh,'Location','BestOutside','Orientation','horizontal')
hold on;

% Aligning errorbar to individual bar within groups
% Based on barweb.m by Bolu Ajiboye from MATLAB File Exchange
groupwidth = min(0.8, 4/(4+1.5));
for i = 1:4
x = (1:6) - groupwidth/2 + (2*i-1) * groupwidth / (2*4);
errorbar(x,mm(i,:),ci(i,:),'k', 'linestyle', 'none');
end``````