2017-05-01 118 views
1

我想将数据添加到matlab中的分组条形图。但是,我无法将每个数据放在每个栏的顶部。对于通常的酒吧和this one使用this question,我尝试了以下代码分组图表,但是xpos和ypos不正确。任何帮助表示赞赏。将数据标签添加到matlab中的分组条形图

a=[0.92,0.48,0.49]; 
b=[0.74,0.60,0.30]; 
c=[0.70,0.30,0.10]; 
X=[a;b;c]; 
hbar = bar(X, 'grouped'); 
    for i=1:length(hbar) 
      XDATA=get(hbar(i),'XData')'; 
      YDATA=get(hbar(i),'YData')'; 
      labels = cellstr(num2str(YDATA)); 
      ygap=0.01; 
      for j=1:size(XDATA,2) 
       xpos=XDATA(i,1); 
       ypos=YDATA(i,1)+ygap; 
       t=[num2str(YDATA(1,j),3)];text(xpos,ypos,t,'Color','k','HorizontalAlignment','left','Rotation',90) 
      end 
    end 
+0

您可以编辑您的问题,包括一些示例数据('X' )。那样我们可以运行代码? [mcve] – Justin

+0

我改变了代码来添加一些数据Mr. @Justin。谢谢 – hamideh

回答

1

有在代码两种主要的错误:

  • 内环的定义:XDATA(N x 1)阵列因此内环使得只有一个迭代以来size(XDATA,2)1。这使你的标签添加每组
  • 在你第一次设置变量t为标签(t=[num2str(YDATA(1,j),3)];的innser环的中心棒;然后你使用相同的变量作为text功能(t = text(xpos,ypos,labels{i});的输出;然后你使用在另一个调用text变量,但现在它包含了手柄的标签,不再标签字符串。这产生一个错误。

要适当的增加,你必须修改代码,以确定该X标签标签的位置

你必须ret请重新选择组中每个小节的位置:每个小节的X位置由其XDATA值给出,加上其相对于组中心的偏移量。偏移值存储在酒吧的XOffset属性中(注意:这是一个hidden/undocumented property)。

这是一个可能的实现:

% Generate some data 
bar_data=rand(4,4) 
% Get the max value of data (used ot det the YLIM) 
mx=max(bar_data(:)) 
% Draw the grouped bars 
hbar=bar(bar_data) 
% Set the axes YLIM (increaed wrt the max data value to have room for the 
% label 
ylim([0 mx*1.2]) 
grid minor 
% Get the XDATA 
XDATA=get(hbar(1),'XData')'; 
% Define the vertical offset of the labels 
ygap=mx*0.1; 
% Loop over the bar's group 
for i=1:length(hbar) 
    % Get the YDATA of the i-th bar in each group 
    YDATA=get(hbar(i),'YData')'; 
    % Loop over the groups 
    for j=1:length(XDATA) 
     % Get the XPOS of the j-th bar 
     xpos=XDATA(j); 
     % Get the height of the bar and increment it with the offset 
     ypos=YDATA(j)+ygap; 
     % Define the labels 
     labels=[num2str(YDATA(j),3)]; 
     % Add the labels 
     t = text(xpos+hbar(i).XOffset,ypos,labels,'Color','k','HorizontalAlignment','center','Rotation',90) 
    end 
end 

​​3210

希望这有助于

Qapla”

+0

完美:)这工作得很好,上帝保佑你:) – hamideh

+0

不客气。快乐我一直在使用你。 –

相关问题