Plot absolute values in stacked bar plot

1 回表示 (過去 30 日間)
Lisa Rosenblum
Lisa Rosenblum 2023 年 1 月 17 日
コメント済み: Dyuman Joshi 2023 年 1 月 18 日
Dear all,
I am creating a stacked bar plot showing ABSOLUTE values (see figure attached).
I am wondering how I can plot the absolute, not the relative numbers, on the seperate bar segments (as depicted by white numbers on the attached plot).
Thank you and all the best,
Lisa
  2 件のコメント
Dyuman Joshi
Dyuman Joshi 2023 年 1 月 17 日
Please attach your data or give a sample data.
Lisa Rosenblum
Lisa Rosenblum 2023 年 1 月 18 日
Hi Dyuman, attached please find the code.
The final plot should look like the on on the previously attached file.
Thanks you so much!
x = [ 15 40 22; 6 13 4];
ba = bar(X,'stacked','FaceColor','flat')
ylim([0 100])
leg = legend({'1','2','3'})
ylabel(['%'])
xticklabels({'Yes', 'No'})
a = get(gca,'XTickLabel');
set(gca,'XTickLabel',a,'fontsize',16)
legend boxoff

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

回答 (1 件)

Dyuman Joshi
Dyuman Joshi 2023 年 1 月 18 日
x = [15 40 22; 6 13 4];
b = bar(x,'stacked','FaceColor','flat');
ylim([0 100])
legend({'1','2','3'});
ylabel('%')
xticklabels({'Yes', 'No'})
a = get(gca,'XTickLabel');
set(gca,'XTickLabel',a,'fontsize',16)
%defining x and y coordinates and labels
xt = [1 2 1 2 1 2];
yt = reshape(cumsum(x,2),1,[])-2;
label = reshape(x,1,[]);
text(xt,yt,string(label),'HorizontalAlignment','center','FontSize',7,'Color','k')
%white didn't look good
legend boxoff
  2 件のコメント
Elli
Elli 2023 年 1 月 18 日
Great, that works perfect! Thanks!
Which part would need to be adjusted if working with more than two bars? For example with an input variable such as
x = [15 40 22; 6 13 4; 17 30 5];
Dyuman Joshi
Dyuman Joshi 2023 年 1 月 18 日
@Elli, that would be like this -
x = [15 40 22; 6 13 4; 17 30 5];
b = bar(x,'stacked','FaceColor','flat');
ylim([0 100])
legend({'1','2','3'});
ylabel('%')
xticklabels({'Yes', 'No'})
a = get(gca,'XTickLabel');
set(gca,'XTickLabel',a,'fontsize',16)
%defining x and y coordinates and labels
%part adjusted
%you can verify the code by using any numbers of rows in your data
r = size(x,1);
xt = repmat([1:r],1, r);
yt = reshape(cumsum(x,2),1,[])-2;
label = reshape(x,1,[]);
text(xt,yt,string(label),'HorizontalAlignment','center','FontSize',7,'Color','k')
%white didn't look good
legend boxoff

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

カテゴリ

Help Center および File ExchangeGraphics Object Properties についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by