# Stacked histogram or Stacked bar

26 views (last 30 days)
shahid saleem on 8 Oct 2020
Commented: Mohammad Sami on 9 Oct 2020
I want to plot the following:
I am able to get the followIng:
using the code below:
[N,edges] = histcounts(GTDF);
edges=[0 300 700 1200 2300]; %redefine the edges
[N,edges] = histcounts(GTDF,edges);
histogram(GTDF, edges, 'Normalization','probability', 'DisplayStyle','bar')
both diagrams are technically the same (percentage of counts and edges etc) but visually different. I want achieve the first diagram.
The reason i Want the first diagram is that i want to plot multiple of these Bars (as shown in first diagram) in the same window and diagram
The data is attached:

Mohammad Sami on 8 Oct 2020
You can try the following
edges=[0 300 700 1200 2300 Inf]; %redefine the edges
[N,edges] = histcounts(GTDF,edges);
N = N./sum(N);
N(2,:) = NaN;
bar(N,'stacked');

shahid saleem on 8 Oct 2020
This works as intendd. Only a few things missing. I would be thankful if you can suggest solution for those as well:
When I plot your solution i get following
1. There is only 1 vertical bar, but why is there number 2 on the X-axis (read arrow)
2. how do I change the name under bar (blue error)
3. can I turn on the grid inside this whole figure? or edge lines corrsponding to each block to show the percentage OR
4. how do show the percentage inside each block (black rectangles
5. Assuming I have different data now, how do I add a second such bar
i have tried:
hold on
but it overwrites the exiting bar instead of placing the second bar next to 1st bar
Lastly, how can i get the legend of ranges such as <300 (color), 300-700 (color) ... etc as shown in the first image of the question
Thanks a lot for answering my questions
Mohammad Sami on 9 Oct 2020
The number 2 is shown because of the line.
N(2,:) = NaN;
This is needed, otherwise Matlab does not plot in stacked mode if there is one row.
You can change it to actual data if you have actual data to plot. This will plot a second bar.
% N(2,:) = N2; % second bar
The following will plot two bars, add legend, turn on grid, change the xtick labels.
edges=[0 300 700 1200 2300 Inf]; %redefine the edges
[N,edges] = histcounts(GTDF,edges);
N = N./sum(N);
N(2,:) = N;
b = bar(N,'stacked');
xticks([1 2]);
xticklabels({'Some Label' 'Something Else'});
b(1).DisplayName = '<300';
b(2).DisplayName = '300-700';
b(3).DisplayName = '700-1200';
b(4).DisplayName = '1200-2300';
b(5).DisplayName = '>2300';
legend show
grid on
Mohammad Sami on 9 Oct 2020
You can add percentages using text function. You need to pass x,y coordinates and text values.
ytext = cumsum(N,2) - 0.04; %y position of text
xtext = ones(size(ytext));
xtext = xtext + [0:1]' %x position of text
textval = string(N*100);
text(xtext(:),ytext(:),textval(:));

R2020a

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!