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

15 vues (au cours des 30 derniers jours)
feihong xu
feihong xu le 23 Juin 2020
Commenté : feihong xu le 25 Juin 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?
  2 commentaires
feihong xu
feihong xu le 24 Juin 2020
Thank you very much!

Connectez-vous pour commenter.

Réponse acceptée

Adam Danz
Adam Danz le 24 Juin 2020
Modifié(e) : Adam Danz le 24 Juin 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)

Plus de réponses (0)

Community Treasure Hunt

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

Start Hunting!

Translated by