5

我有一个数组a(30,2),其中第一列是唯一的样本编号,第二列是分配给样本的值。我绘制了第二列的直方图:

hist(a(:,2))

我有N垃圾箱,y 轴告诉我有多少样本的值为 x,但没有关于哪些样本在哪个垃圾箱中的信息。

如何在每个 bin 上方绘制a落入每个 bin 的样本列表(数组第一列的数字)?

4

3 回答 3

5

正如@Jonas@Itamar Katz所示,想法是使用 HISTC 获取每个样本所属的 bin 索引,然后使用 BAR 绘制结果(注意我们使用'histc'BAR 函数的显示模式) . 我在下面的回答是@Jonas 帖子的变体:

[编辑]

%# random data
a = [(1:30)' rand(30,1)];                %'#

%# compute edges (evenly divide range into bins)
nBins = 10;
edges = linspace(min(a(:,2)), max(a(:,2)), nBins+1);

%# compute center of bins (used as x-coord for labels)
bins = ( edges(1:end-1) + edges(2:end) ) / 2;

%# histc
[counts,binIdx] = histc(a(:,2), edges);
counts(end-1) = sum(counts(end-1:end));  %# combine last two bins
counts(end) = [];                        %# 
binIdx(binIdx==nBins+1) = nBins;         %# also fix the last bin index

%# plot histogram
bar(edges(1:end-1), counts, 'histc')
%#bar(bins, counts, 'hist')              %# same thing
ylabel('Count'), xlabel('Bins')

%# format the axis
set(gca, 'FontSize',9, ...
    'XLim',[edges(1) edges(end)], ...    %# set x-limit to edges
    'YLim',[0 2*max(counts)], ...        %# expand ylimit to accommodate labels
    'XTick',edges, ...                   %# set xticks  on the bin edges
    'XTickLabel',num2str(edges','%.2f')) %'# round to 2-digits

%# add the labels, vertically aligned on top of the bars
hTxt = zeros(nBins,1);                   %# store the handles
for b=1:nBins
    hTxt(b) = text(bins(b), counts(b)+0.25, num2str(a(b==binIdx,1)), ...
        'FontWeight','bold', 'FontSize',8, 'EdgeColor','red', ...
        'VerticalAlignment','bottom', 'HorizontalAlignment','center');
end

%# set the y-limit according to the extent of the text
extnt = cell2mat( get(hTxt,'Extent') );
mx = max( extnt(:,2)+extnt(:,4) );       %# bottom+height
ylim([0 mx]);

替代文字

如果 x 轴上的刻度变得太拥挤,您可以使用XTICKLABEL_ROTATE函数(在 FEX 上提交)以一定角度旋转显示它们。

于 2011-01-11T22:57:10.603 回答
4

首先,按照@Itamar Katz的建议,使用HISTC创建一个直方图。要使 bin 与HIST相同,您需要正确计算 bin 边缘。然后,您可以绘制分布并使用TEXTNUM2STR添加标签。

%# get the edges, bin centers
nBins = 10;
edges = linspace(min(a(:,2),max(a(:,2),nBins+1); %# edges go from minimum to maximum of distribution
bins = (edges(1:end-1)+edges(2:end))/2;

%# get the counts and the bin-index
[counts,binIdx] = histc(a(:,2),edges);

%# plot the counts and bins (not edges) with `bar`
figure
bar(bins,counts);

%# Set the axes limits such that you have enough space for the labels
ylim([0,2*max(counts)]);

%# add the labels. Vertically align such that the text goes from the y-coordinate
%# down (as opposed to being centered on the y-coordinate).
for b = 1:nBins
    text(bins(b),counts(b)*2,num2str(a(b==binIdx,1)),'VerticalAlignment','top')
end
于 2011-01-11T13:46:51.953 回答
1

使用histc,它为每个条目返回一个索引,它“下降”到哪个 bin:

[n, bin] = histc (a(:, 2), bins);

那么第 k 个 bin 上方的样本为:

a(bin==k, 1);

请注意,您必须自己指定 bin 的边界(与hist使用边界之间的中间值不同)。

于 2011-01-11T13:19:08.370 回答