# How to specify labels on stacked bar plot

5 views (last 30 days)
Commented: Mathieu NOE on 3 Apr 2023
I am trying to created a stacked bar plot that has 6 bars per category, and I would like to plot all 3 categories at once.
So far, I managed to get the 3 categories together like this:
The blank spaces between the 3 categories is just a zero I've added to the array.
This almost works, but I need to rename the x-axis to the names of the categories ('State 1', 'State 2', 'State 3') under each collection of 6 bars. However, using the information from https://de.mathworks.com/help/matlab/ref/bar.html I don't suceed, as the dimensions of the categorical variable doesn't match the dimension of the array being plotted.
Here is what I have as of now:
y = [];
for i = 1:length(some_vector)
a = vector_of_values;
b = another_vector_of_values;
y = [y; [[a, b]; [0 0]]]; % 0 0 to create spacing between the diff. states
end
x = categorical({'State1' 'State 2' 'State 3'});
bar(x, y, 'stacked');
legend('Config 1', 'Config 2')
I'm not quite sure how I can force one of the dimensions to be only 3 (dimension of x) since I have 6 bars and each bar needs 2 entries (that will stack on top of each other).
Thanks for the help!

Mathieu NOE on 31 Mar 2023
Hello
maybe this ?
y = [];
states = 3;
for i = 1:states
a = rand(5,1);
b = rand(5,1);
y = [y; [[a, b]; [0 0]]]; % 0 0 to create spacing between the diff. states
end
x = categorical({'State1' 'State 2' 'State 3'});
bar(y, 'stacked');
[m,n] = size(a);
new_xticks = (m/2) + (0:i-1)*(m+1); % +1 because the separator between groups
set(gca,'XTick',new_xticks,'XTicklabel',x)
legend('Config 1', 'Config 2')
##### 2 CommentsShow 1 older commentHide 1 older comment
Mathieu NOE on 3 Apr 2023
as always, my pleasure !

### Categories

Find more on Annotations in Help Center and File Exchange

R2020b

### Community Treasure Hunt

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

Start Hunting!

Translated by