如何在直方图箱上方显示标签?

Rob*_*rtD 5 matlab plot histogram

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

hist(a(:,2))
Run Code Online (Sandbox Code Playgroud)

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

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

Amr*_*mro 5

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

[EDITED]

%# 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]);
Run Code Online (Sandbox Code Playgroud)

替代文字

如果x轴上的刻度变得过于拥挤,则可以使用XTICKLABEL_ROTATE函数(在FEX上提交)以角度显示它们.


Ita*_*atz 1

使用histc,它返回每个条目的索引,它“落在”哪个容器中:

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

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

a(bin==k, 1);

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