How to specify labels on stacked bar plot

4 次查看(过去 30 天)
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
Mathieu NOE 2023-3-31
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')

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Line Plots 的更多信息

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by