您可以使用unique
和histc
函数来获取唯一值和频率计数,然后使用bar
中的'stacked'
选项绘制数据。请注意,在下面,我已将level
和age
作为列向量。我还将代码的核心部分作为一般而不是这个特定的例子。
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')
+1不错的使用ACCUMARRAY的。我通过在HISTC调用中不对硬编码值[10 11]进行硬编码,而是使用'uniqAge = unique(data(:,2));'来使代码更一般化。此外,这里还需要传说:'legend(strtrim(cellstr(num2str(uniqAge,'Age%d'))),'Location','NorthWest')' – Amro
@Amro:好的建议。我已经相应地更新了代码。 – gnovice