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

18 次查看(过去 30 天)

采纳的回答

MathWorks Support Team
编辑: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: 

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Axis Labels 的更多信息

产品


版本

尚未输入任何版本。

Community Treasure Hunt

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

Start Hunting!

Translated by