How do I label the bars in my bar graph in MATLAB?
18 次查看(过去 30 天)
显示 更早的评论
MathWorks Support Team
2013-10-18
编辑: MathWorks Support Team
2025-2-4
How do I label the bars of a bar plot created using the "bar" function?
采纳的回答
MathWorks Support Team
2025-1-17
编辑:MathWorks Support Team
2025-2-4
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 个评论
Kevin Gleason
2016-9-27
Hi Artem,
Perhaps you are looking for something like this:
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Axis Labels 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!