Clear Filters
Clear Filters

How do I display a value on bar?

49 views (last 30 days)
ocsse
ocsse on 23 Sep 2018
Commented: Star Strider on 3 May 2022
How can I display the value at the top of each bar? assume that I have the following bar plot:

Accepted Answer

Star Strider
Star Strider on 23 Sep 2018
Try this (if you have R2014b or later):
y1 = [2 2 3; 2 5 6; 2 8 9; 2 11 12];
hBar = bar(y1,1); % Return ‘bar’ Handle
for k1 = 1:size(y1,2)
ctr(k1,:) = bsxfun(@plus, hBar(1).XData, hBar(k1).XOffset'); % Note: ‘XOffset’ Is An Undocumented Feature, This Selects The ‘bar’ Centres
ydt(k1,:) = hBar(k1).YData; % Individual Bar Heights
text(ctr(k1,:), ydt(k1,:), sprintfc('%.1f', ydt(k1,:)), 'HorizontalAlignment','center', 'VerticalAlignment','bottom', 'FontSize',8, 'Color','b')
end
the sprintfc function is undocumented. It is essentially the same as sprintf, and augmented to produce a cell array of outputs. This makes it very efficient in situations such as this, where the result is a cell array.
  2 Comments
SOMNATH MAHATO
SOMNATH MAHATO on 3 May 2022
if the vlaue is more than 4 then its not working
y1 = [0.433 0.177 0.768 1.224; 0.379 0.158 0.267 0.320; 0.0406 0.016 0.031 0.0380; 0.0972 0.0371 0.0538 0.0483; 0.0777 0.0324 0.0552 0.0660];
can you solve this?
Star Strider
Star Strider on 3 May 2022
It works correctly with your data when I run it here —
y1 = [0.433 0.177 0.768 1.224; 0.379 0.158 0.267 0.320; 0.0406 0.016 0.031 0.0380; 0.0972 0.0371 0.0538 0.0483; 0.0777 0.0324 0.0552 0.0660];
hBar = bar(y1,1); % Return ‘bar’ Handle
for k1 = 1:size(y1,2)
ctr(k1,:) = bsxfun(@plus, hBar(1).XData, hBar(k1).XOffset'); % Note: ‘XOffset’ Is An Undocumented Feature, This Selects The ‘bar’ Centres
ydt(k1,:) = hBar(k1).YData; % Individual Bar Heights
text(ctr(k1,:), ydt(k1,:), sprintfc('%.1f', ydt(k1,:)), 'HorizontalAlignment','center', 'VerticalAlignment','bottom', 'FontSize',8, 'Color','b')
end
.

Sign in to comment.

More Answers (0)

Categories

Find more on Printing and Saving 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!