arjun
arjun

Reputation: 31

how to add data labels for bar graph in matlab

For example (code):

x = [3 6 2 9 5 1];
bar(x)

for this I need to add data labels on top of the each bar. I know that I have to use TEXT keyword, but I'm not getting how to implement it.

Upvotes: 3

Views: 6557

Answers (3)

EBH
EBH

Reputation: 10450

Here is a simple solution with text:

x = [3 6 2 9 5 1];
bar(x)
ylim([0 max(x)*1.2])
text(1:numel(x),x+0.5,num2cell(x))

data labels in bar

Upvotes: 1

Fthi.a.Abadi
Fthi.a.Abadi

Reputation: 322

After some attempts I have found the solution. Do the following:

y = Data;
for b = 1 : 10
    BarPlot(b) = bar(b, y(b), 'BarWidth', 0.9); % actual plot
    set(BarPlot(b), 'FaceColor', 'blue'); %Apply color
    barTopper = sprintf('%.1f%s', y(b)*100,'%'); % Place text on top
    text(b-0.5, y(b)+0.01, barTopper, 'FontSize', barFontSize); % position the text
    hold on;
end

Let me know if it works.

Upvotes: 0

Dan
Dan

Reputation: 45762

Based off this answer:

data = [3 6 2 9 5 1];
figure; %// Create new figure
hbar = bar(data);    %// Create bar plot
%// Get the data for all the bars that were plotted
x = get(hbar,'XData');
y = get(hbar,'YData');
ygap = 0.1;  %// Specify vertical gap between the bar and label
ylimits = get(gca,'YLim');

%// The following two lines have minor tweaks from the original answer
set(gca,'YLim',[ylimits(1),ylimits(2)+0.2*max(y)]);
labels = cellstr(num2str(data'))                                   %//'

for i = 1:length(x) %// Loop over each bar
    xpos = x(i);        %// Set x position for the text label
    ypos = y(i) + ygap; %// Set y position, including gap
    htext = text(xpos,ypos,labels{i});          %// Add text label
    set(htext,'VerticalAlignment','bottom', 'HorizontalAlignment','center')
end

Upvotes: 0

Related Questions