How do I automatically annotate a 2D bar graph with corresponding p-values for each bar?

22 次查看(过去 30 天)
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!

采纳的回答

Jonathan Epperl
Jonathan Epperl 2012-11-29
编辑:Jonathan Epperl 2012-12-7
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:
  1. 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
  2. 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
  3. 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.
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 个评论
jpfeifer
jpfeifer 2016-1-26
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

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Specifying Target for Graphics Output 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by