How to draw negative values on bar when it contains negative values
조회 수: 5 (최근 30일)
이전 댓글 표시
if my data have negative values
I want to draw the bar values uniformly on the top of the bar chart, like the numbers above 0 on the way, and the values below 0 are all drawn inside the bar chart
clear all ; clc ;clf
yyy = [1 2 3 4 ; 2 3 -4 5 ; -6 -10 5 7 ; -1 -5 8 7]
x = [1:4]
bar1 = bar(x,yyy)
hAx=gca; % get a variable for the current axes handle
% hAx.XTickLabel=str; % label the ticks
hT=[]; % placeholder for text object handles
for i=1:length(bar1) % iterate over number of bar objects
hT=[hT text(bar1(i).XData+bar1(i).XOffset,bar1(i).YData,num2str(bar1(i).YData.','%.3f'), ...
'VerticalAlignment','bottom','horizontalalign','center')];
end
댓글 수: 0
채택된 답변
dpb
2022년 9월 26일
편집: dpb
2022년 9월 27일
That's a little more tricky and the examples don't illustrate -- but it's not terribly difficult to fix; the problem is 'VerticalAlignment' property needs to be sensitive to the sign of the data. One either has to do a double-index loop or keep the loop by bar handle and then fixup each position in the end...
y = [1 2 3 4 ; 2 3 -4 5 ; -6 -10 5 7 ; -1 -5 8 7];
hB=bar(y);
% preallocate the text handles for text objects NB bars are by column; but
% text handles are row vector so transpose to preallocate the text object handles
hTxt=gobjects(size(y.'));
% iterate over bar groups; again NB row vector of text handles returned by text
for i=1:numel(hB)
hTxt(i,:)=text(hB(i).XData+hB(i).XOffset,hB(i).YData,num2str(hB(i).YData.','%d'), ...
'VerticalAlignment','bottom','horizontalalign','center');
end
% now the magic fixup by sign for vertical alignment -- can set all at once after the fact
set(hTxt((y.'<0)),{'VerticalAlign'},{'top'})
ylim(12*[-1 1]) % make a little more room to put labels inside box
The alternative is one has to write a second loop over the number of YData values in each bar handle and use if/else construct on each value to set the alignment.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Annotations에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!