How to specify labels on stacked bar plot

13 Ansichten (letzte 30 Tage)
Joao Henrique Faller Moura
Joao Henrique Faller Moura am 31 Mär. 2023
Kommentiert: Mathieu NOE am 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!

Akzeptierte Antwort

Mathieu NOE
Mathieu NOE am 31 Mär. 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 Kommentare
Joao Henrique Faller Moura
Joao Henrique Faller Moura am 31 Mär. 2023
That works just as I needed it! Thank you a lot! :)
Mathieu NOE
Mathieu NOE am 3 Apr. 2023
as always, my pleasure !

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Line Plots finden Sie in Help Center und File Exchange

Produkte


Version

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by