How do I label the bars in my bar graph in MATLAB?
18 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
MathWorks Support Team
le 18 Oct 2013
Modifié(e) : MathWorks Support Team
le 4 Fév 2025
How do I label the bars of a bar plot created using the "bar" function?
Réponse acceptée
MathWorks Support Team
le 17 Jan 2025
Modifié(e) : MathWorks Support Team
le 4 Fév 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:
2 commentaires
Kevin Gleason
le 27 Sep 2016
Hi Artem,
Perhaps you are looking for something like this:
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Axis Labels dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!