How to add proper values on top of bar chart

9 ビュー (過去 30 日間)
Elias Klee
Elias Klee 2022 年 11 月 21 日
回答済み: David Hill 2022 年 11 月 21 日
Hi,
I'm using the code below to create a bar chart:
Y1 = [-31.6 15.8 -8.0]
subplot(3,2,2)
bar(2,Vn4a_diff,'FaceColor',[0 0.6 0.3],'EdgeColor',[0 0 0])
hold on
grid on
xlim([0.5 3.5])
xticks([1 2 3])
xticklabels({'z','y','yz'})
ylabel(['Spannung (MPa)'])
ylim([-50 50])
bar(1,Vn4c_diff,'FaceColor',[1 0.2 0.2],'EdgeColor',[0 0 0])
bar(3,Vn4b_diff,'FaceColor',[0 0.5 1],'EdgeColor',[0 0 0])
text(1:length(Y1),Y1,num2str(Y1'),'vert','bottom','horiz','center');
box off
Unfortunately, in the resulting chart the values are colliding with the bars itself. I'd love to have a solution where the values are depicted on top of the bars instead of into them, does someone have a solution? Thanks in advance!

回答 (2 件)

Star Strider
Star Strider 2022 年 11 月 21 日
There are too many missing variables to run the posted code.
Try something like this (requires two separate text calls) —
Y1 = [-31.6 15.8 -8.0];
figure
bar(Y1)
x = 1:3;
text(x(Y1<0), Y1(Y1<0), compose('%g',Y1(Y1<0)), 'Horiz','center', 'Vert','top') % Negative Bars
text(x(Y1>0), Y1(Y1>0), compose('%g',Y1(Y1>0)), 'Horiz','center', 'Vert','bottom') % Positive Bars
That should be relatively straightforward to adapt to your existing code.
.

David Hill
David Hill 2022 年 11 月 21 日
Y1 = [-31.6 15.8 -8.0];
subplot(3,2,2)
Vn4a_diff=15.8;Vn4c_diff=-31.6;Vn4b_diff=8;
b=bar(2,Vn4a_diff,'FaceColor',[0 0.6 0.3],'EdgeColor',[0 0 0]);
text(b.XEndPoints,b.YEndPoints,string(b.YData),'vert','bottom','horiz','center');
hold on
grid on
xlim([0.5 3.5])
xticks([1 2 3])
xticklabels({'z','y','yz'})
ylabel('Spannung (MPa)')
ylim([-50 50])
b=bar(1,Vn4c_diff,'FaceColor',[1 0.2 0.2],'EdgeColor',[0 0 0]);
text(b.XEndPoints,b.YEndPoints-20,string(b.YData),'vert','bottom','horiz','center');
b=bar(3,Vn4b_diff,'FaceColor',[0 0.5 1],'EdgeColor',[0 0 0]);
text(b.XEndPoints,b.YEndPoints,string(b.YData),'vert','bottom','horiz','center');
box off

カテゴリ

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

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by