Stacked Bar Graph Matlab

C. Reed picture C. Reed · Jun 20, 2011 · Viewed 15.1k times · Source

Say I have data as follows:

 level,age
     8,10
     8,11
     8,11
     9,10
     9,11
     9,11
     9,11

I'm looking to form a stacked bar graph in Matlab where "level" is on the x-axis and number of occurances of that level (the frequency) is on the y-axis: so 8 would have a y-value of 3 and 9 would have a y-value of 4. Furthermore, I'm looking to have this as a stacked bar chart so level 8 would have 1 unit colored green (green is age 10) and 2 units colored red (where red is age 11) and 9 would have 1 unit colored green and 3 units colored red.

Thanks for any help!

Answer

gnovice picture gnovice · Jun 20, 2011

You can do this in a fairly compact and general way using the function ACCUMARRAY like so, where data is your 7-by-2 sample matrix of data:

ageValues = unique(data(:,2));          %# Vector of unique age values
barData = accumarray(data(:,1),data(:,2),[],@(x) {hist(x,ageValues)});
X = find(~cellfun('isempty',barData));  %# Find x values for bars
Y = vertcat(barData{:});                %# Matrix of y values for bars
hBar = bar(X,Y,'stacked');              %# Create a stacked histogram
set(hBar,{'FaceColor'},{'g';'r'});      %# Set bar colors
legend(cellstr(num2str(ageValues)),'Location','NorthWest');  %# Add a legend

Note that the cell array of colors {'g';'r'} passed to the function SET in the second-to-last line should have the same number of elements as ageValues to function properly.

And here's the resulting bar graph:

enter image description here