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

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

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 17 Jan 2025
Edited: MathWorks Support Team on 4 Feb 2025
From MATLAB R2019b, this workflow has been implemented with the use of XEndPoint and YEndPoint. To access the release-specific documentation for MATLAB R2020b, please execute the following command in the MATLAB command window:
>> web(fullfile(docroot, 'matlab/ref/bar.html'))
Prior to MATLAB R2019b, you could programmatically add text labels above the bars on a plot. These labels serve to highlight notable features of the dataset, such as statistical significance or associated p-values for each bar. This is accomplished using a "for" loop that iterates over each bar in the plot, adding an appropriate label with the "text" function. Below is an example code to demonstrate this approach:
%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 required for groups of bars, the x coordinates passed to the "text" function will need to be adjusted so that the text is placed correctly over each bar. This adjustment is necessary because "hbar" in the above code is a vector of handles, and the x and y coordinates of the text label must be modified for each group.
Please use the below link to search for the required information in the current release: 

More Answers (0)

Products


Release

No release entered yet.

Community Treasure Hunt

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

Start Hunting!