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

时间:2011-01-11 12:42:36

标签: matlab plot histogram

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

hist(a(:,2))

我有N个分区,y轴告诉我有多少个样本的值为x, 但没有关于哪个样本在哪个bin中的信息。

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

3 个答案:

答案 0 :(得分:5)

正如@Jonas@Itamar Katz所示,我们的想法是使用HISTC获取每个样本所属的bin索引,然后使用BAR绘制结果(注意我们使用的是BAR功能的'histc'显示模式)。我在下面的回答是@ 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]);

alt text

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

答案 1 :(得分:4)

首先,按照HISTC的建议,使用@Itamar Katz创建直方图。要使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

答案 2 :(得分:1)

使用histc,它会为每个条目返回一个索引,以便它“落入”哪个bin:

  

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

然后第k个bin上方的样本是:

  

a(bin == k,1);

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