How to Plot Numbers on top of Bar graphs?
37 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
AZ Sajjad
el 22 de Oct. de 2022
Editada: Musalula Sinkala
el 20 de Dic. de 2022
clc;
close all;
clear;
components = {'First Design', 'Second Design', 'Third Design'};
x = [66.5 33.5; 68.7 31.3; 64.9 35.1];
y = bar(x,'grouped');
xticklabels(components);
grid on
xlabel ('Design Name','fontweight','bold','FontSize',12);
ylabel ('Penetration Level (%)','fontweight','bold','FontSize',12);
legend('DG', 'PV');
0 comentarios
Respuesta aceptada
Star Strider
el 22 de Oct. de 2022
Try this —
components = {'First Design', 'Second Design', 'Third Design'};
x = [66.5 33.5; 68.7 31.3; 64.9 35.1];
figure
y = bar(x,'grouped');
xtips1 = y(1).XEndPoints;
ytips1 = y(1).YEndPoints;
labels1 = string(y(1).YData);
text(xtips1,ytips1,labels1,'HorizontalAlignment','center',...
'VerticalAlignment','bottom')
xtips2 = y(2).XEndPoints;
ytips2 = y(2).YEndPoints;
labels2 = string(y(2).YData);
text(xtips2,ytips2,labels2,'HorizontalAlignment','center',...
'VerticalAlignment','bottom')
xticklabels(components);
grid on
xlabel ('Design Name','fontweight','bold','FontSize',12);
ylabel ('Penetration Level (%)','fontweight','bold','FontSize',12);
legend('DG', 'PV');
ylim([min(ylim) 75])
This should work in most recent releases. If it does not work in your release (since you did not specify that, I have no idea what it is), there are other options that will work. For the present, see the bar documentation section on Specify Labels at the Ends of Bars for details.
.
5 comentarios
Más respuestas (2)
MarKf
el 22 de Oct. de 2022
Editada: MarKf
el 22 de Oct. de 2022
Something like this?
Edit: ah, too slow. Though this very basic approach might work with earlier releases too. You could get() the x coords for the text from the bar handle too
components = {'First Design', 'Second Design', 'Third Design'};
x = [66.5 33.5; 68.7 31.3; 64.9 35.1];
ybar= bar(x,'grouped');
xticklabels(components);
grid on
xlabel ('Design Name','fontweight','bold','FontSize',12);
ylabel ('Penetration Level (%)','fontweight','bold','FontSize',12);
legend('DG', 'PV');
[r,c]=size(x);
ybuff=2;
for ri = 1:r
for ci = 1:c
text(ri+(-0.15+0.3*(ci-1)),x(ri,ci)+ybuff,num2str(x(ri,ci),'%0.0f%%'),...
'HorizontalAlignment','center',...
'VerticalAlignment','bottom')
end
end
ylim([0 100])
Musalula Sinkala
el 20 de Dic. de 2022
Editada: Musalula Sinkala
el 20 de Dic. de 2022
A simple loop will do
figure()
bv = bar(x,'grouped');
% add the numbers
for ii = 1:numel(bv)
% the positions
xLoc = bv(ii).XEndPoints;
yLoc = bv(ii).YEndPoints;
% labels with %
theLabels = strcat( string(yLoc),'%') ;
% a vectorised one liner
text(xLoc, yLoc, theLabels, 'vert','bottom','horiz','center');
end
0 comentarios
Ver también
Categorías
Más información sobre Line Plots en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!