Data labels above bars on grouped bar plot

조회 수: 139 (최근 30일)
Justin Solomon
Justin Solomon 2014년 5월 16일
댓글: Image Analyst 2022년 7월 15일
I'm making a grouped bar plot (i.e., a bar plot with multiple bars in each category). I would like to add labels at the top of each bar to indicate its height. I was planning to just use the text function. However, bars within a given group all have the same x location (i.e get(h,'XData') is the same for all bar series). I'm not sure how to find the proper x location for each bar within a given group. Any ideas?
Thanks, Justin
  댓글 수: 2
K E
K E 2016년 6월 30일
Matlab should offer bar labels as part of the bar function since bar plots are often presented this way. Really appreciate the workaround answers below though!
dpb
dpb 2016년 6월 30일
Submit the enhancement request to TMW @ www.mathworks.com

댓글을 달려면 로그인하십시오.

채택된 답변

dpb
dpb 2014년 5월 16일
편집: dpb 2014년 5월 16일
You're on the right track, the center of each group is at the axis tick value. For each bar in the group, use that value plus/minus a delta to locate the x position for your text.
I did an example of this for another poster within the last few weeks at most altho I don't have the link at hand. Perhaps a search will uncover it.
ADDENDUM:
OK, I looked at past answers--this one is pretty close altho I thought I did another. Maybe it was in the newsgroup instead...
  댓글 수: 6
Mostafa Darvishi
Mostafa Darvishi 2016년 10월 3일
Hello, I just tumbled into this post and I found it very interesting in my application. in this tripple bar plot, you used the array of [4 3] that means 4 intervals with 3 bars in each interval. But the function that you have used is a random number generator. My question is that how should I change the code in the case that I have 3 arrays as functions. For example I have three following arrays and I want to plot them in triple plot.
Y1 = [1 3 6 7 9 12 11]; Y2 = [12 5 8 13 11 1 4]; Y3 = [11 31 16 17 7 113 15];
dpb
dpb 2016년 10월 3일
Just past 'em together...
Y=[Y1;Y2;Y3].'; % create nx3 column array for *bar*
NB: The latest release of bar uses HG2 and returns a handle to a barobject, rather than the former bar series objects. This new object is essentially opaque to the the details and the data for the patches used to draw the bars isn't available from which to compute the individual bar positions so labelling bars as this example does won't work. I've not got a more recent version so not sure what the workaround is, if there is one or if one must resort back to the earlier "trick" I illustrated before.

댓글을 달려면 로그인하십시오.

추가 답변 (5개)

Will Adler
Will Adler 2014년 11월 18일
This doesn't work in R2014b any more, due to this.
The available bar series properties no longer have the info for the location of the bar. Any idea how to recreate this in grouped bar plots?
  댓글 수: 8
dpb
dpb 2016년 9월 21일
What's the issue, specifically? The x-position for the text object to write is given by the above; simply modify the y-position to place where wanted in the bar instead above it--the y distances are computable directly from the data; don't need similar machinations as do for x.
I was thinking I'd seen additional properties mentioned that were useful having been introduced in HG2 but a search the other day didn't seem to find such, unfortunately, so guess I had mixed up with something else.
Kelly Kearney
Kelly Kearney 2016년 9월 21일
Moving the labels inside the bars is a simple matter of changing the horizontal alignment so the right edge, rather than left, aligns with the bar height (and in most cases, adding a small offset to the y-position so the text doesn't sit flush to the bar edge).
This example also assumes that your bars are all large enough to fit the full text string.
Y=random('unif',30,100,[4 3]); % sample data
h=bar(Y);
yb = cat(1, h.YData);
xb = bsxfun(@plus, h(1).XData, [h.XOffset]');
hold on;
padval = 1;
htxt = text(xb(:),yb(:)-padval, cellstr(num2str(yb(:))), ...
'rotation', 90, 'horiz', 'right');
set(htxt(1:3:end), 'color', 'w'); % for legibility

댓글을 달려면 로그인하십시오.


Image Analyst
Image Analyst 2014년 5월 17일
For what it's worth, see attached demo. Adapt as needed.
  댓글 수: 1
Justin Solomon
Justin Solomon 2014년 5월 17일
Thanks for your comments. The difference in the case you show here and my case is that your bars are all centered on the ticks. If you have bar groups, then you have multiple bars grouped about the same xtick (see the image link in my original post). The only way I was able to figure out the exact center location of the each bar within a group was to get info from the underlying patch objects that are created when bar() is called. See my code above for an example.

댓글을 달려면 로그인하십시오.


aliyar attaran
aliyar attaran 2016년 11월 4일
for 2 bars one one y value:
for i2=1:numel(y)
tx(i2,1)=text(x(i2),y(i2,1),num2str(y(i2,1),'%0.2f'),...
'HorizontalAlignment','right',...
'VerticalAlignment','bottom');
tx(i2,2)=text(x(i2),y(i2,2),num2str(y(i2,2),'%0.2f'),...
'HorizontalAlignment','left',...
'VerticalAlignment','bottom');
end

Elimelech Schreiber
Elimelech Schreiber 2017년 11월 5일
I've written a function to do just this. It's called barvalues, and is very easy yo use.
simply:
bar(x);
barvalues;
  댓글 수: 3
dpb
dpb 2017년 11월 6일
편집: dpb 2017년 11월 6일
I munged on your function some...haven't tested it thoroughly but it now works for the above case...haven't tried for more exotic examples. I know it won't work correctly for 'stacked' as the YData property isn't correct y location for it--not sure if it is retrievable or must be recomputed.
Modifications include
  1. fixing up isaType to look at all objects in handle array rather than just one (this may be too simplistic in some cases, I don't know; didn't study the search logic enough to know if could possibly pass a group that might be other than bar handles)
  2. using only one of the array handles in axes call to get axes handle (this could also possibly(?) be too simplistic if there are multiple bar objects but in multiple axes on a given figure), and
  3. looping over the handle array and adding the .XOffSet property differential to the text call.
Doesn't seem an easy way to add updates at the Exchange so I'll just paste the modified routine here for your convenience...
Giuseppe Naselli
Giuseppe Naselli 2022년 7월 15일
Thanks for the barvalues function Elimelech, very easy to use and solid
Very appreciated
G

댓글을 달려면 로그인하십시오.


Halina H
Halina H 2017년 12월 7일
Hi , I would like to know how to code to get the total value of each bar in this grouped bar graph ie , total bincounts for the yellow bar, total bincounts for blue bar , and total bincounts for green bar. I am interested to know which of these 3 bars give the most information
  댓글 수: 1
Image Analyst
Image Analyst 2022년 7월 15일
Since you plotted the 3 sets of data, you already have the counts. If you want the total number of counts, that's simply the number of elements in the data that you took the histogram of.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Graphics Object Properties에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by