2015-07-10 27 views
0

我在下圖中生成直方圖(在x軸上有一天中的幾小時)。 任何想法如何圍繞最高價值?在這種情況下,我想把正確的部分放在第一個箱子的左邊...直方圖小時日(連續箱)

時間是一個cellarray包含12天的時間戳(1分鐘分辨率)。

Time{1,1}='00:00:00'; 
Time{2,1}='00:01:00'; 
... 
Time{1000,1}='16:39:00'; 
... 
Time{17280,1}='23:59:00' 

睡覺是一個載體,如果主體正在睡覺0,如果不是。

sleeping(1,1)=1; 
sleeping(2,1)=1; 
... 
sleeping(1000,1)=0; 
... 
sleeping(17280,1)=1; 



    figure 
    hist(datenum(Time(sleeping==1)),24) 
    datetick 

enter image description here

+2

您可以編輯問題以包含生成此圖的代碼嗎?第二天不是右邊的部分,因此並不真正反映第一天的觀察結果嗎? – Matt

+0

是的,但不管它屬於哪一天...我對小時直方圖感興趣.... – gabboshow

+0

你對所有小時的直方圖感興趣嗎? (例如,任何一天的上午3點都是同一個垃圾箱)或者您對每天的每小時直方圖感興趣? (無論哪種方式,您的代碼都有問題)。 – nkjt

回答

0

首先,使用歷史記錄,以返回直方圖的值(vals)和箱(bins):

[vals, bins] = hist(datenum(Time(sleeping==1)),24); 

然後,找出其中最大實際是,在爲了使直方圖相對於最大值居中:

[val, idx] = max(vals); 

然後,獲取直方圖中心的位置(如果使用24 -bin直方圖,則應爲12)。然後,估計將直方圖中心移動到繪圖中心所需的移位量。

centerPos = round(length(bins)/2); 
shiftSize = centerPos - idx; 

找到shiftSize後,我們可以有三種情況:一),移動至左側,在這種情況下,這一轉變將是更大的。我處理這個如下:

if shiftSize < 0 % move to the left w.r.t. center 
    shiftSize = length(bins) - shiftSize; 
end 

此外,B)如果移位是正確的,那麼就沒有必要更新shiftSize。然後,c)shiftSize爲零,這意味着不需要轉移。在這兩個最後的情況下,沒有必要改變shiftSize

在的)和b),我們現在執行的循環移位(如@Luis Mendo建議)情況:

if shiftSize % if it is 0 it means that it is already centered 
    nvals = circshift(vals, shiftSize, 2); 
    nbins = circshift(bins, shiftSize, 2); 
end 

最後,我們的情節,並獲得當前軸進行調節。

figure, bar(bins, nvals); ax = gca; 

現在,您確保您擁有所有24小時的所有垃圾箱。

ax.XTick = bins; 

這裏需要注意的是,如果你這樣做ax.XTick = nbins它會給你一個錯誤,因爲XTICK必須單調遞增。最後,你讓那些x軸標籤爲轉移的人改變:

ax.XTickLabel = datestr(nbins, 'HH:MM'); 

下面是例如您提供完整的代碼

Time{1,1}='00:00:00'; 
Time{2,1}='00:01:00'; 
Time{1000,1}='16:39:00'; 
Time{17280,1}='23:59:00'; 

sleeping(1,1)=1; 
sleeping(2,1)=1; 
sleeping(1000,1)=0; 
sleeping(17280,1)=1; 

[vals, bins] = hist(datenum(Time(sleeping==1)),24); 

% get the maximum 
[val, idx] = max(vals); 

% circularly shift to center around the maximum 
centerPos = round(length(bins)/2); 
shiftSize = centerPos - idx; 
if shiftSize < 0 % move to the left w.r.t. center 
    shiftSize = length(bins) - shiftSize; 
end 

if shiftSize % if it is 0 it means that it is already centered 
    nvals = circshift(vals, shiftSize, 2); 
    nbins = circshift(bins, shiftSize, 2); 
end 

figure, bar(bins,nvals); ax = gca; 
ax.XTick = bins; 
ax.XTickLabel = datestr(nbins, 'HH:MM'); 

這給了我以下劇情:

Centered along the max :)

讓我KN如果你有問題,請告訴我。