Effacer les filtres
Effacer les filtres

How to post the values in the middle of a stacked bar plot?

14 vues (au cours des 30 derniers jours)
Jolien de Boer
Jolien de Boer le 10 Juil 2022
Commenté : Voss le 11 Juil 2022
Hi!
I'm new to MatLab and I want to make a plot with the values present in the middle of the bars.
x = [0 0 20 52.5 27.5; 5 10 50 20 15; 2.5 5 25 47.5 20; 5 5 42.5 45 2.5; 2.5 27.5 40 27.5 2.5; 2.5 12.5 65 20 0]
bar (x, 'stacked')
  1 commentaire
dpb
dpb le 10 Juil 2022
Dunno what you mean??? Going to have to do more than that to explain...you know what you want, we only know what you tell us.

Connectez-vous pour commenter.

Réponse acceptée

Voss
Voss le 10 Juil 2022
Modifié(e) : Voss le 10 Juil 2022
x = [0 0 20 52.5 27.5; 5 10 50 20 15; 2.5 5 25 47.5 20; 5 5 42.5 45 2.5; 2.5 27.5 40 27.5 2.5; 2.5 12.5 65 20 0]
x = 6×5
0 0 20.0000 52.5000 27.5000 5.0000 10.0000 50.0000 20.0000 15.0000 2.5000 5.0000 25.0000 47.5000 20.0000 5.0000 5.0000 42.5000 45.0000 2.5000 2.5000 27.5000 40.0000 27.5000 2.5000 2.5000 12.5000 65.0000 20.0000 0
[m,n] = size(x);
xx = (1:m).'+zeros(1,n); % x-coordinates of texts, for both methods below
One way, using the properties of the bar objects created with bar:
h = bar (x, 'stacked');
ydata = cell2mat(get(h,'YData'));
yendpoints = cell2mat(get(h,'YEndPoints'));
yy = (yendpoints-ydata/2).'; % y-coordinates of texts
text(xx(:),yy(:),sprintfc('%.1f',x),'HorizontalAlignment','center')
Another way, using just the data x:
figure
bar (x, 'stacked');
yy = cumsum([zeros(m,1) x],2);
yy = (yy(:,1:end-1)+yy(:,2:end))/2; % y-coordinates of texts
text(xx(:),yy(:),sprintfc('%.1f',x),'HorizontalAlignment','center')
Notice that bars with zero height are labeled '0.0'. You can omit the labels for zero-height bars:
figure
bar (x, 'stacked');
% calculate yy using either of the above methods
idx = x ~= 0;
text(xx(idx),yy(idx),sprintfc('%.1f',x(idx)),'HorizontalAlignment','center')
  2 commentaires
Jolien de Boer
Jolien de Boer le 11 Juil 2022
Thank you so much!
Voss
Voss le 11 Juil 2022
You're welcome!

Connectez-vous pour commenter.

Plus de réponses (0)

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by