How to draw negative values ​​on bar when it contains negative values

6 次查看(过去 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

采纳的回答

dpb
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 CenterFile Exchange 中查找有关 Annotations 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by