- hy = bar(y) returns the handles of the barseries objects that have been created, one for each column of y. The plot, however, consists of groups of bars, one group for each row of y. So the handle hy(1) will correspond to the first bars in all the groups and so on
- Each hy(i) in turn has one Child, and that is the patch that makes up the bars. The patches have properties 'XData' and 'YData', which contain the corners of the patches that bar(y) created
- So in the outer for loop I go through all the 1st, 2nd, 3rd bars and in the inner one I go through each group of bars and place the p-value over them.
How do I automatically annotate a 2D bar graph with corresponding p-values for each bar?
12 views (last 30 days)
Show older comments
I would like to display the p-values on top of a bar graph.
Here's what I have:
y = [1 2 3; 4, 4, 5; 6, 7, 6];
p = rand(3,3)
figure
bar(y)
p_flat = reshape(p', 1, 9);
y_flat = reshape(y', 1, 9);
for ii = 1:9
text(ii, p_flat(ii)+2, ['p=' num2str(p_flat(ii))])
end
The problem is that only three p-values are being displayed, and they are in the wrong spot.
How do I make it so that the p-values are on top of the correct bar?
Thanks!
0 Comments
Accepted Answer
Jonathan Epperl
on 29 Nov 2012
Edited: Jonathan Epperl
on 7 Dec 2012
bar is a funny animal, it took me a little bit to figure out what's going on. First, the code that should be doing what you want it to do:
hy = bar(y)
for i=1:3
X = get( get(hy(i),'Children'), 'XData');
Y = get( get(hy(i),'Children'), 'YData');
for j = 1:size(X,2)
text(X(3,j)/2+X(2,j)/2,Y(3,j)+.1,num2str(p(j,i),'p = %f'),'Rotation',90);
end
end
Here is some explanation:
If you don't like that the highest bar has its text outside the axis, add something like
set(gca,'YLim',[0 max(y(:)+2)]);
If you have negative y-values it gets a little more tricky, but lets assume you don't.
2 Comments
jpfeifer
on 26 Jan 2016
For newer versions, you can use something along the lines of
hy = bar(y);
for i=1:size(hy,2)
X = hy(i).XData;
Y = hy(i).YData;
for j = 1:size(X,2)
text(X(1,j)-(2-i)*0.3*hy(i).BarWidth,Y(1,j)+.1,num2str(p(j,i),'p = %f'),'Rotation',90);
end
end
More Answers (0)
See Also
Categories
Find more on Specifying Target for Graphics Output 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!