C. Reed
C. Reed

Reputation: 2452

Stacked Bar Graph Matlab

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!

Upvotes: 6

Views: 15263

Answers (2)

gnovice
gnovice

Reputation: 125854

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

Upvotes: 5

abcd
abcd

Reputation: 42225

You can do what you want using the unique and histc functions to get the unique values and frequency counts and then use the 'stacked' option in bar to plot the data. Note that in the following, I have taken level and age to be column vectors. I've also made the central parts of the code general instead of for this specific example.

level=[8,8,8,9,9,9,9]';              %'#SO code formatting
age=[10,11,11,10,11,11,11]';         %'

%#get unique values and frequency count
uniqLevel=unique(level);
freqLevel=histc(level,uniqLevel);    
uniqAge=unique(age);

%#combine data in a manner suitable for bar(...,'stacked')
barMatrix=cell2mat(arrayfun(@(x)histc(age(level==uniqLevel(x)),uniqAge),...
    1:numel(uniqLevel),'UniformOutput',false));

%#plot the stacked bars and customize
hb=bar(barMatrix','stacked');        %'

set(gca,'xticklabel',uniqLevel,'ytick',1:max(sum(barMatrix)))
set(hb(uniqAge==10),'facecolor','green')
set(hb(uniqAge==11),'facecolor','red')

xlabel('Level')
ylabel('Occurrence')
legend('10','11','location','northwest')

enter image description here

Upvotes: 3

Related Questions