# How to Plot Numbers on top of Bar graphs?

1,412 ビュー (過去 30 日間)
Ibro Tutic 2017 年 8 月 7 日

Assume we have this as data
Y=[198 138 172 188 190 192];
bar(Y);
How would I go about plotting the Y-values of each of the bars on top of the bars? So each bar would show its value on top of it.

サインインしてコメントする。

### 採用された回答

Chad Greene 2017 年 8 月 7 日

Use the text function like this:
Y=[198 138 172 188 190 192];
bar(Y);
text(1:length(Y),Y,num2str(Y'),'vert','bottom','horiz','center');
box off
##### 3 件のコメント表示非表示 2 件の古いコメント
Chad Greene 2017 年 11 月 20 日
The phrase "it isn't working" does not contain enough information to help. I suggest reading this, then start another question with specifics about the issue you're having.

サインインしてコメントする。

### その他の回答 (2 件)

Johannes Stoerkle 2020 年 2 月 21 日

As an extension, I found a good approach if one wants to plot the number on the top of bars, which are displayed in several groups. Therefore, I estimate the correction for the text x-Position using an exp-function, which is fitted to my empirical results.
For instance. If you consider 3 categories and 7 different models (determined in first line) it results:
dataSample = reshape([36 2:21],3,7)';
figure
catStrArray = {'category1','category2','category3'};
catArray = categorical(catStrArray);
catArray = reordercats(catArray,catStrArray);
bar(catArray,dataSample')
nModel = size(dataSample,1);
nCat = size(dataSample,2);
xPosAmpl = 0.3682626-0.3298725*exp(-0.407004*(nModel-1)); % position amplitude
xPosInc = 2*xPosAmpl/(nModel-1);
modelNames = [];
for idxModel=1:nModel
bar_xPos = 1:nCat;
if nModel~=1
bar_xPos = bar_xPos-xPosAmpl+(idxModel-1)*xPosInc;
end
text(bar_xPos,dataSample(idxModel,:),num2str(dataSample(idxModel,:)',...
'%0.0f'),'vert','bottom','horiz','center');
modelNames{idxModel}=sprintf('model%d',idxModel);
end
legend(modelNames)
##### 0 件のコメント表示非表示 -1 件の古いコメント

サインインしてコメントする。

Soyeun Jung 2017 年 8 月 7 日
Hi Ibro, you can run this line of code to display the y-values on top of each bar. See the attached link for related information. https://ch.mathworks.com/matlabcentral/answers/40629-bar-plot-value-on-top
text([1:length(Y)], Y', num2str(Y','%0.2f'),'HorizontalAlignment','center','VerticalAlignment','bottom')

サインインしてコメントする。

### Community Treasure Hunt

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

Start Hunting!

Translated by