直方图小时日(连续箱)

histograms hours day (continuous bins)

我生成了下图中的直方图(x 轴上是一天中的几个小时)。 知道如何以最高价值为中心吗?在这种情况下,我想将右侧部分放在第一个箱子的左侧旁边...

Time 是一个包含 12 天时间戳(1 分钟分辨率)的 cellarray。

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

睡眠是一个向量,如果主体正在睡觉则包含 1,否则为 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

首先,使用 hist 来 return 直方图的值 (vals) 和 bins (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后,我们可以有三种情况: a) 向左移动,这种情况下移动会更大。我处理如下:

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

此外,b) 如果向右移动,则无需更新shiftSize。那么,c)shiftSize为零,即不需要移位。在后两种情况下,无需更改 shiftSize.

对于 a) 和 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');

这给了我以下情节:

如果您有任何问题,请告诉我。