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

标签 matlab plot histogram

我有一个数组 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/

相关文章:

matlab - 避免 MATLAB 图形中的文本重叠

python - MATLAB 到 Python : How to replace nargin functionality

performance - 快速检查元素是否在MATLAB矩阵中

r - 在 ggplot geom_path 中添加轻微的曲线(或弯曲)以使路径更易于阅读

r - 如何可视化组和子组频率?

matlab - MATLAB 中的颜色编码二维图

python - 如何批量获取 PyTorch 张量的直方图?

sql - 从 SQL Server 表为直方图创建范围箱

java - 打开太多图形时如何避免 MATLAB 崩溃?

matlab:二维线图水平线