MATLAB: How to label the bars in the bar graph in MATLAB

bargraphinsertlabel;MATLABp-valueplotsignificancestatistical

How do I label the bars of a bar plot created using the "bar" function?

Best Answer

From MATLAB R2019b this workflow have been implemented with the use of XEndPoint and YEndPoint : https://www.mathworks.com/help/releases/R2020b/matlab/ref/bar.html?#mw_735ee38d-9d9f-40cd-b02a-8266af7184d9
 
Before MATLAB R2019b, it is possible to programmatically add text labels above the bars on a plot. These labels can be used to indicate any interesting features of the data set, such as statistical significance or the associated p-values of each bar.This can be done using a "for" loop that loops over each bar in the plot and adds an appropriate label using the "text" function. Refer to the following example code for a simple demonstration on how to do this: 
    % Generate random data
    data = 10*rand(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');
    set(gca,'YLim',[ylimits(1),ylimits(2)+0.2*max(y)]); % Increase y limit for labels
    % Create labels to place over bars
    labels = {'A', ['A';'B';'*'],'AB','',['A ';'**']}; 
    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',...  % Adjust properties
                      'HorizontalAlignment','center')
    end
Note that if labels are desired for groups of bars, the x coordinates passed to the "text" function will need to be modified so that the text is placed over the correct bar. This can be done in a similar manner but taking into account that "hbar" in the above code is a vector of handles, and that the x and y coordinates of the text label must be adjusted for each group.