Clear Filters
Clear Filters

How to decrease the font size of the values that are above each bar in the chart?

2 views (last 30 days)
I would like to know how to decrease the font size of the values that are above each bar in the chart. I would appreciate your answers. Attached is some code.
clf;
x4=categorical(["Ciclista"; "Material"; "Ocupante"; "Peatón"]);
y4 = [6 40 5; 1500 691 21; 0 307 4; 0 106 22];
b4=bar(x4,y4, 'FaceColor','flat');
cm = gray(5); % Define 'colormap'
for k = 1:numel(b3)
b4(k).CData = cm(k+1,:); % Loop To Set Colours
end
ylim([0 1900])
xtips4 = b4(1).XEndPoints;
ytips4 = b4(1).YEndPoints;
labels4 = string(b4(1).YData);
text(xtips4,ytips4,labels4,'HorizontalAlignment','center',...
'VerticalAlignment','bottom')
xtips4 = b4(2).XEndPoints;
ytips4 = b4(2).YEndPoints;
labels4 = string(b4(2).YData);
text(xtips4,ytips4,labels4,'HorizontalAlignment','center',...
'VerticalAlignment','bottom')
xtips4 = b4(3).XEndPoints;
ytips4 = b4(3).YEndPoints;
labels4 = string(b4(3).YData);
text(xtips4,ytips4,labels4,'HorizontalAlignment','center',...
'VerticalAlignment','bottom')
% legend('Accidente','Lesionado','Muerte')
legend({'Accidente','Lesionado','Muerte'},'Location','north','Orientation','horizontal')
legend('boxoff');
xlabel("Víctimas de accidentes");
ylabel("Número de víctimas");
txt = {'a)'};
text(200,335,0.56,txt, 'FontSize',14, 'FontName','Times New Roman');

Answers (1)

dpb
dpb on 29 Jul 2023
Edited: dpb on 1 Aug 2023
FONTSIZE=8;
x4=categorical(["Ciclista"; "Material"; "Ocupante"; "Peatón"]);
y4 = [6 40 5; 1500 691 21; 0 307 4; 0 106 22];
b4=bar(x4,y4, 'FaceColor','flat');
cm = gray(5); % Define 'colormap'
set(b4,{'CData'},mat2cell(cm(2:4,:),ones(size(b4))))
ylim([0 1900])
hTxt=arrayfun(@(h)text(h.XEndPoints,h.YEndPoints,string(h.YData), ...
'Horizontal','center','Vertical','bottom','FontSize',FONTSIZE),b4,'UniformOutput',false);
% legend('Accidente','Lesionado','Muerte')
legend({'Accidente','Lesionado','Muerte'},'Location','north','Orientation','horizontal')
legend('boxoff');
xlabel("Víctimas de accidentes");
ylabel("Número de víctimas");
To set font size as variable up top, but primarily to illustrate how to set properties and the text objects using vectorized version of set and then with the implicit loop via arrayfun to do the annotations to reduce code bulk.

Community Treasure Hunt

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

Start Hunting!