How to put a numerical value inside a Bar graph?

Hi!
I'd like to know how can I set the values inside the bar plot, just like this:
I obtain the following bar plot using the code above but I can't place values in the correct center position.
b = bar(X,Y);
hold on
b.FaceColor = 'flat';
b.CData(1,:) = [0 0.447 0.741]; % color editing
b.CData(2,:) = [0.850 0.325 0.098];
b.CData(3,:) = [0.466 0.674 0.188];
b.FaceAlpha = .7; % opacity
text(1:length(Y),Y,num2str(Y'),'vert','bottom','horiz','center'); % values position
std = [2.1 4.4 6]; % standard deviation
er = errorbar(X,Y,std);
er.Color = [0 0 0];
er.LineStyle = 'none';
set(gca, 'ytick', []);
box off
Can you help me, please?
Thank you,
Sara

1 件のコメント

KSSV
KSSV 2020 年 11 月 29 日
Read about text, annotation.

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

 採用された回答

Star Strider
Star Strider 2020 年 11 月 29 日

0 投票

Change the text call to:
text(1:length(Y),Y/2,num2str(Y'),'vert','bottom','horiz','center'); % values position
That should work, if I understand correctly what you want to do.
.

4 件のコメント

Sara Macchiavello
Sara Macchiavello 2020 年 11 月 29 日
編集済み: Sara Macchiavello 2020 年 11 月 29 日
Yes, perfect it works. Thank you!
Another question: how can I print also '%' after the numbers?
I undersood that num2str(Y') print the number but I can't insert the percentage.
Star Strider
Star Strider 2020 年 11 月 29 日
As always, my pleasure!
There are a few different ways to add the ‘%’:
text(1:length(Y),Y/2,[num2str(Y') ['%';'%';'%']],'vert','bottom','horiz','center'); % values position
text(1:length(Y),Y/2,sprintfc('%g%%',Y),'vert','bottom','horiz','center'); % values position
text(1:length(Y),Y/2,compose('%g%%',Y),'vert','bottom','horiz','center'); % values position
The first concatenates the ‘['%';'%';'%']’ vector to the num2str vector, the second and third use different functions to create a cell array of strings that prints the value with the ‘%’. Since the ‘%’ is a valid cointrol character to those functions, to print one ‘%’ it is necessary to use '%%', (The same is true for other control characters in these and similar functions.)
Sara Macchiavello
Sara Macchiavello 2020 年 11 月 29 日
Thank you very much for your advice and explaination, you're really kind!!
Star Strider
Star Strider 2020 年 11 月 29 日
As always, my pleasure!
I very much appreciate your compliment!

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeDiscrete Data Plots についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by