gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 19:39:46 27 4
gpt4 key购买 nike

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

hist(a(:,2))

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

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

最佳答案

@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]);

alt text

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

关于matlab - 如何在直方图箱上方显示标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4657719/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com