How to add lables on each coloumn of grouped stacked bar chart?

48 views (last 30 days)
feihong xu
feihong xu on 23 Jun 2020
Commented: feihong xu on 25 Jun 2020
Hello,
I used the function of Plot Groups of Stacked Bars to make the grouped stacked bar chart, and I used this method to change the color of each bar.
Here is what I made:
This is what I would like to add on top of each coloumn:
Can some one tell me how to put the lable on top on earch coloum?

Accepted Answer

Adam Danz
Adam Danz on 24 Jun 2020
Edited: Adam Danz on 24 Jun 2020
h is the array of handled that you added as an output to the PlotBarsStackGroup function from the file exchange.
To add the labels to the top of the bars
% Detect number of groups.
nGroups = numel(h(1,1).YData);
% Define labels for groups of 5 bars
labels = {'Lancaster','Cincinnati','Sofia','Rochester','Boston'};
% Compute the height of each bar stack and add label to top
offset = range(ylim)*.01;
for i = 1:size(h,1)
ysum = sum(reshape([h(i,:).YData],nGroups,[]),2);
text(h(i,1).XData,ysum+offset,labels{i},'HorizontalAlignment','left',...
'VerticalAlignment','middle','rotation',90)
end
You may need to change the ylim() so the labels do not run off of the upper axis limits.
Here's an alternative that does not use a loop.
% Get the (x,y) coordinates for the top of each bar stack
y = sum(reshape(cell2mat(get(h', 'YData')),size(h,2),[]),1);
x = unique(cell2mat(get(h', 'XData')),'stable')
% Define labels, then replicate them for all groups
labels = {'Lancaster','Cincinnati','Sofia','Rochester','Boston'};
allLabels = repmat(labels,1,numel(h(1).XData));
% Plot the text labels
offset = range(ylim)*.01;
th = text(x,y+offset,allLabels,'HorizontalAlignment','left',...
'VerticalAlignment','middle','rotation',90)

More Answers (0)

Community Treasure Hunt

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

Start Hunting!