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

6 views (last 30 days)
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'), ...

Accepted Answer

dpb on 26 Sep 2022
Edited: dpb on 27 Sep 2022
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];
% 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
% 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'), ...
% now the magic fixup by sign for vertical alignment -- can set all at once after the fact
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.

More Answers (0)


Find more on Environment and Settings in Help Center and File Exchange


Community Treasure Hunt

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

Start Hunting!