How do I label the bars in my bar graph in MATLAB?
조회 수: 70 (최근 30일)
이전 댓글 표시
MathWorks Support Team
2013년 10월 18일
편집: MathWorks Support Team
2020년 10월 20일
How do I label the bars of a bar plot created using the "bar" function?
채택된 답변
MathWorks Support Team
2020년 10월 20일
편집: MathWorks Support Team
2020년 10월 20일
From MATLAB R2019b this workflow have been implemented with the use of XEndPoint and YEndPoint : https://www.mathworks.com/help/releases/R2020b/matlab/ref/bar.html?#mw_735ee38d-9d9f-40cd-b02a-8266af7184d9
Before MATLAB R2019b, it is possible to programmatically add text labels above the bars on a plot. These labels can be used to indicate any interesting features of the data set, such as statistical significance or the associated p-values of each bar.This can be done using a "for" loop that loops over each bar in the plot and adds an appropriate label using the "text" function. Refer to the following example code for a simple demonstration on how to do this:
% 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 desired for groups of bars, the x coordinates passed to the "text" function will need to be modified so that the text is placed over the correct bar. This can be done in a similar manner but taking into account that "hbar" in the above code is a vector of handles, and that the x and y coordinates of the text label must be adjusted for each group.
댓글 수: 2
Kevin Gleason
2016년 9월 27일
Hi Artem,
Perhaps you are looking for something like this:
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Graphics Object Properties에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!