How to draw negative values on bar when it contains negative values
12 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposta accettata
dpb
il 26 Set 2022
Modificato: dpb
il 27 Set 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];
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.
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Annotations in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!