2017-05-01 122 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

不客氣。快樂我一直在使用你。 –

相關問題