MATLAB: How do i label each bar in bar group with a “string” on top

barstringtext;top

Hi ! Urgent help needed. I have a grouped bar graph and i want to add text on the top of each bar in each group. I am doing this way:
y = [58.1395 62.7907; 40.3900 40.3400]
Y=bar(y)
str={'John'; 'Adam'};
set(gca, 'XTickLabel',str, 'XTick',1:numel(str))
labels= {'Physics', 'Chemistry'; 'Physics', 'Chemistry'};
xt = get(gca, 'XTick');
text(xt, y, labels, 'HorizontalAlignment','center', 'VerticalAlignment','bottom')
Am getting error "error using text Value must be a column or row vector in bar plot" and not able to fix it. Am working in R2015b. Help me.

Best Answer

...
hB=bar(y); % use a meaningful variable for a handle array...
hAx=gca; % get a variable for the current axes handle
hAx.XTickLabel=str; % label the ticks
hT=[]; % placeholder for text object handles

for i=1:length(hB) % iterate over number of bar objects

hT=[hT text(hB(i).XData+hB(i).XOffset,hB(i).YData,num2str(hB(i).YData.','%.3f'), ...
'VerticalAlignment','bottom','horizontalalign','center')];
end
The text command does the two groups with the two bars of each group labeled in the one call for each bar group. The x position is that of the data plus the offset and the y position is the data value. The label is formatted to string to be written by num2str; note carefully the transpose operator .' to create a column vector; this is imperative or the two values would be strung together on a single line.
The "trick" is in the hB.XOffset term; the 'XOffset' property is hidden so have to know it exists a priori as there's nothing to give away its existence nor any other data available from which to compute the dX that the routine uses internally for the offset of the bar center from the x location of the group. As noted above, this is a real foopah on TMW's part...
The above results in
ADDENDUM
Specifically addressing the concern that didn't do the labels,
hT=[]; % placeholder for text object handles
for i=1:length(hB) % iterate over number of bar objects
hT=[hT,text(hB(i).XData+hB(i).XOffset,hB(i).YData,labels(:,i), ...
'VerticalAlignment','bottom','horizontalalign','center')];
end
results in
instead...