MATLAB Answers

Help with centralling text values above a Bar Chart with side by side data

조회 수: 4(최근 30일)
Jason
Jason 8 Jan 2020
편집: Jason 10 Jan 2020
Hello, I am plottign a barchart from data from a uitable. I have 2 ydata sets that I plot next to each other as below.
im138.png
I am wanting to display the values on each column bar and I have almost done it. But they are not quite central with respect to the bars. Here is my code:
%Get data from UITABLE
data=get(handles.uitable3,'data');
Y=cell2mat(data(:,4));
X=data(:,2);
%Prepare for catergorical X data
Xdata = categorical(X);
X = reordercats(Xdata,X);
axes(handles.axes2);cla reset
%Combine Y data and create bar chart
Y1=cell2mat(data(:,3));
bpcombined = [Y, Y1];
hb = bar(X, bpcombined, 'grouped');
legend({'400-800nm','FilterBand'},'Location','northoutside','FontSize',10,'NumColumns',2)
%Add text to top of barcharts
for i1=1:numel(Y1)
text(X(i1),Y1(i1),num2str(Y1(i1),'%0.0f'),...
'HorizontalAlignment','left',...
'VerticalAlignment','bottom','Color','w')
text(X(i1),Y(i1),num2str(Y(i1),'%0.0f'),...
'HorizontalAlignment','right',...
'VerticalAlignment','bottom','Color','w')
end
%Sometimes the txt is off the plot so resize the ylims (Maybe there is a better way to do this!)
if max(ylim)>=Y(end)
ylim([0 1.10*Y(end)])
end
%Add the axtoolbar (This isn't working for some reason)
ax=gca;
axtoolbar(ax,{'export','restoreview','zoomout','zoomin'});
axtoolbar(ax,'Visible','on')
drawnow;

  댓글 수: 1

로그인 to comment.

채택된 답변

Rik
Rik 10 Jan 2020
Find the x position of the bar itself and use that in your call to text. Then you can set the HorizontalAlignment to center.

  댓글 수: 3

Jason
Jason 10 Jan 2020
I have tried this:
hb(1).XData %hb is my barchart handle
But it just returns an array of the catergories
ans =
1×3 categorical array
405nm_1 405nm_2 405nm_3
Jason
Jason
Jason 10 Jan 2020
OK I think with Rik's suggestion I have worked it out.
When you plot catergorical data X is actually plots at locations x=1,2,3 etc.
Its the offset between groups that we need:
offset=hb(1).XOffset %hb is mt barchart handle
So I can loop through my catergorical data (X(i))
but put the x coordiante intext to be i + offset
Jason
Rik
Rik 10 Jan 2020
Glad to have been of help. Sorry for my slow response, I'm a bit busy today. Good to see you solved it.

로그인 to comment.

추가 답변(0개)

이 질문에 답변하려면 로그인을(를) 수행하십시오.

태그


Translated by