Effacer les filtres
Effacer les filtres

How do I display a value on bar?

49 vues (au cours des 30 derniers jours)
ocsse
ocsse le 23 Sep 2018
Commenté : Star Strider le 3 Mai 2022
How can I display the value at the top of each bar? assume that I have the following bar plot:

Réponse acceptée

Star Strider
Star Strider le 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 commentaires
SOMNATH MAHATO
SOMNATH MAHATO le 3 Mai 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 le 3 Mai 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
.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Printing and Saving dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by