How to post the values in the middle of a stacked bar plot?
21 ビュー (過去 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
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
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]
[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 Center および File Exchange で Annotations についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!