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

14 次查看(过去 30 天)
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 个评论
dpb
dpb 2022-7-10
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.

请先登录,再进行评论。

采纳的回答

Voss
Voss 2022-7-10
编辑:Voss 2022-7-10
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')

更多回答(0 个)

类别

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

标签

Community Treasure Hunt

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

Start Hunting!

Translated by