Matlab Folded Bar Graph

Say I have data as follows:

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

I am looking to form a glass-broken histogram in Matlab where the β€œlevel” is on the x axis and the number of events of this level (frequency) is on the y axis: so 8 will have a y- value of 3 and 9 will have a y value 4. In addition, I want it to be like a complex histogram, so level 8 will have 1 unit of color green (green age 10) and 2 units of red color (where red is 11 years old), and 9 is 1 unit of color green colors and 3 units of red.

Thanks for any help!

+6
source share
2 answers

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

 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 

Please note that the array of color cells {'g';'r'} passed to the SET function in the second or last line must have the same number of elements as ageValues to work correctly.

And here is the resulting histogram :

enter image description here

+5
source

You can do what you want using unique and histc to get unique values ​​and frequency, and then use the 'stacked' option in bar to print the data. Note that later on I took level and age as column vectors. I also made the central parts of the code, not 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

+3
source

Source: https://habr.com/ru/post/890888/


All Articles