How to add proper values on top of bar chart
24 次查看(过去 30 天)
显示 更早的评论
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!

0 个评论
回答(2 个)
Star Strider
2022-11-21
There are too many missing variables to run the posted code.
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.
.
0 个评论
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
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!