MATLAB: How to add error bars on bar graph with groups

bar grapherror bars

Hi all,
I'm trying to create a bar graph with error bars.
So far, my code is:
c = categorical({'CH','VC','GC','OC','BC','SC'});
c = reordercats(c,{'CH','VC','GC','OC','BC','SC'});
y = [707, 599; 464 444; 522 475; 566 346; 1329 1384; 459 498];
std_dev = [321 271; 233 91; 202 132; 0 173; 410 850; 179 122];
title('Title'); xlabel('x-label'); ylabel('y-label');
figure
hold on
bar(c,y)
errorbar(y,std_dev,'.')
The resulting graph is attached. The error bars appear to stack on top of each other, and are between the the two bars in each pair. I'm unsure how to make each error bar match with individual bars.
If it's helpful, the data in y is annual, where the first number (i.e. 707, 464, 522, 566) is Year 1 and the second number (i.e. 599, 444, 475, 346) is Year 2. The groups are further broken down so that the first three groups (c = CH, VC, GC) are one set and the last three (c = OC, BC, SC) are a second set. If possible, I would also like to have the Year 1 and Year 2 be different colors, as well as the two sets. So, for example, 707 = red, 599 = blue, 459 = green, 498 = orange.
Any help getting started is greatly appreciated!
Cheers

Best Answer

Hey there,
I hope this solution covers what you have been looking for.
close all
clear all
clc
y = [707, 599; 464 444; 522 475; 566 346; 1329 1384; 459 498];
std_dev = [321 271; 233 91; 202 132; 0 173; 410 850; 179 122];
num = 6; %number of different subcategories
c = 1:num;
%%Figure
figH = figure;
axes1 = axes;
title('Title'); xlabel('x-label'); ylabel('y-label');
hold on
%%Bar(s)
%You can not color differently the same bar.
for i = 1:num
bar(c(i)-0.15,y(i,1),0.2);
bar(c(i)+0.15,y(i,2),0.2);
end
%%Errorbar
errH1 = errorbar(c-0.15,y(:,1),std_dev(:,1),'.','Color','b');
errH2 = errorbar(c+0.15,y(:,2),std_dev(:,2),'.','Color','r');
errH1.LineWidth = 1.5;
errH2.LineWidth = 1.5;
errH1.Color = [1 0.5 0];
errH2.Color = [1 0.3 1];
%%Set x-ticks
set(axes1,'Xlim',[0.5 5.5]);
set(axes1,'XTick',[1 1.5 2 2.5 3 3.5 4 4.5 5 5.5 6],'XTickLabel',...
{'CH',' ','VC',' ','GC',' ','OC',' ','BC',' ','SC'});
end
If you need more details/comments about the code just let me know. Just the two main problems:
  • Your problem is not that simple... e.g.: you plotted only one bar - which means you have only 2 different data s subsets, that is logically means two different colors.Now to color differently the "subsubsets" ('CH','VC' etc.) and even every bar(!) you have to create a bar for every different colors...
  • The other thing is that you can not position freely your objects when you are working with categorical type. To bypass that just create simple vectors as I did.