2011-06-20 224 views
6

說我有數據如下:堆積條形圖Matlab的

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

我期待以形成在Matlab堆疊條形圖其中,「水平」是在該電平的occurances的x軸和數目(頻率)在y軸上:所以8的y值爲3,9的y值爲4.此外,我希望將此作爲堆疊條形圖,因此8級會有1個單位爲綠色(綠色爲10歲),2個單位爲紅色(紅色爲11歲),9個單位爲綠色,3個單位爲紅色。

感謝您的幫助!

回答

5

你可以在一個相當緊湊和通用的方式使用功能ACCUMARRAY像這樣,在data是數據的7×2樣品基質做到這一點:

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 

請注意,顏色爲{'g';'r'}的單元陣列在倒數第二行中傳遞給功能SET的單元陣列數應與ageValues的功能單元數相同。

而這裏的產生bar graph

enter image description here

+3

+1不錯的使用ACCUMARRAY的。我通過在HISTC調用中不對硬編碼值[10 11]進行硬編碼,而是使用'uniqAge = unique(data(:,2));'來使代碼更一般化。此外,這裏還需要傳說:'legend(strtrim(cellstr(num2str(uniqAge,'Age%d'))),'Location','NorthWest')' – Amro

+0

@Amro:好的建議。我已經相應地更新了代碼。 – gnovice

3

您可以使用uniquehistc函數來獲取唯一值和頻率計數,然後使用bar中的'stacked'選項繪製數據。請注意,在下面,我已將levelage作爲列向量。我還將代碼的核心部分作爲一般而不是這個特定的例子。

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