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

22 Ansichten (letzte 30 Tage)
Rachelle am 28 Nov. 2012
Kommentiert: jpfeifer am 26 Jan. 2016
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 Kommentare-2 ältere Kommentare anzeigen-2 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

### Akzeptierte Antwort

Jonathan Epperl am 29 Nov. 2012
Bearbeitet: Jonathan Epperl am 7 Dez. 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:
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 KommentareKeine anzeigenKeine ausblenden
K E am 24 Dez. 2015
Does not seem to work with R2015b.
jpfeifer am 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

Melden Sie sich an, um zu kommentieren.

### Kategorien

Mehr zu Annotations finden Sie in Help Center und File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by