Filter löschen
Filter löschen

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

14 Ansichten (letzte 30 Tage)
Jolien de Boer
Jolien de Boer am 10 Jul. 2022
Kommentiert: Voss am 11 Jul. 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 Kommentar
dpb
dpb am 10 Jul. 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.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Voss
Voss am 10 Jul. 2022
Bearbeitet: Voss am 10 Jul. 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')

Weitere Antworten (0)

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by