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.

Answers


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

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.


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))


Need Your Help

Memcpy implementation, strict aliasing

c++ c memcpy strict-aliasing

While learning c I have implemented my own memcpy functions. I have used a wider type( uint32_t) in the function. (For simplicity the function is restricted to types that are multiples of 4 and the...