MATLAB: How to stack hist

histstack

Does anyone knows how to stack 2 histogram. I have certain area data for 20 years. I am calculating yearly number of events by hist command. And also I have another area data for 20 years. Doing the same, calculating yearly number of events by hist command for the area also. Note for 2 data time the same, 1980-2000 in years.
Now I wanted 2 hist data stack. Is there any way to do it?
Thanks!

Best Answer

The hist function does not offer a 'stacked' option, but you can create the effect easily enough with the histc function and a bar plot.
Experiment with this to get the result you want with your data:
d1 = randi(9, 50, 1); % Create Data

d2 = randi(9, 50, 1); % Create Data
binrng = 1:9; % Create Bin Ranges
counts1 = histc(d1, binrng); % Histogram For ‘d1’
counts2 = histc(d2, binrng); % Histogram For ‘d2’
counts3 = counts1 + counts2; % Histogram Sum ‘d1’+‘d2’
figure(1)
bar(binrng, counts3, 'b')
hold on
bar(binrng, counts1, 'y')
hold off
legend('Data 1', 'Data 2')
The idea is straightforward: create histogram counts for both sets of data, add them, then use the bar plot to first plot the sum, then overplot with one of the others. That will create your stacked histogram plot.