フィルターのクリア

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

14 ビュー (過去 30 日間)
Jolien de Boer
Jolien de Boer 2022 年 7 月 10 日
コメント済み: Voss 2022 年 7 月 11 日
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')
  2 件のコメント
Jolien de Boer
Jolien de Boer 2022 年 7 月 11 日
Thank you so much!
Voss
Voss 2022 年 7 月 11 日
You're welcome!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeAnnotations についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by