# How do I label the bars in my bar graph in MATLAB?

264 views (last 30 days)
How do I label the bars of a bar plot created using the "bar" function?

MathWorks Support Team on 20 Oct 2020
Edited: MathWorks Support Team on 20 Oct 2020
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
'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.
Kevin Gleason on 27 Sep 2016

Phong Huynh on 12 Jan 2019
Edited: madhan ravi on 12 Jan 2019
this line
set(gca,'YLim',[ylim(1),ylim(2)+0.2*max(y)])
caurses an error If y is a matrix instead of array

### Release

No release entered yet.

### Community Treasure Hunt

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

Start Hunting!