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

29 ビュー (過去 30 日間)
MathWorks Support Team
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
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 件のコメント
K E
K E 2016 年 9 月 19 日
編集済み: K E 2016 年 9 月 19 日
An answer that works for R2016a is here .
Kevin Gleason
Kevin Gleason 2016 年 9 月 27 日

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeAxis Labels についてさらに検索

製品


リリース

リリースが未入力です。

Community Treasure Hunt

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

Start Hunting!

Translated by