how to add data labels for bar graph in matlab

For example (code):

x = [3 6 2 9 5 1];

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.


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

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;

Let me know if it works.

Here is a simple solution with text:

x = [3 6 2 9 5 1];
ylim([0 max(x)*1.2])

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