Matlab - 直方图边缘和切断

Matlab - Histogram edges and cut off

我试图或多或少地复制以下 p-值密度直方图,具有不同的数据:

所以我想创建一个直方图,其中的 bin 刻度位于柱的 beginning/end 处。有 15 个柱,值范围从 0 到 1(包括 1)。

目前我正在使用 histc 命令:

xint=1/15;
edges=(0:xint:1);
[n,bin]=histc(data,edges);
bar(edges,n,'histc');
tit='p-values histogram';
htitle=title(tit);
set(htitle,'fontname','Calibri')
xlabel('p-values');
ylabel('Frequency');

这给了我:

但是,如果数据等于 1,则当前代码会在 1 之后绘制一个新柱。我想我需要包括边缘(以与示例相同),但我似乎做不到找到正确的命令?

另外,如何使直方图在 x=1 处截止,如示例所示?在 0.6 处插入示例的 "lambda arrow" 是可取的(但可选)。

编辑 3 和 4:由于您使用的是没有 histogram 的 Matlab R2013b,因此请使用 hist 绘制:

[n, centers] = hist(data, 15)

请注意,这个 returns centers,而不是 bin 的 edges。对于箭头,如果 R2013b 支持,您可以使用 annotation。或者(有点老套):

line([0.6 0.6], [1750 1250])
plot(0.6, 1250, 'Marker, 'v')
text(0.6, 1750, '\lambda', 'HorizontalAlignment','center', 'VerticalAlignment','bottom')

编辑 2:尝试

xint=1/15;
edges_in=(0:xint:1);
histogram(data,edges_in);

直接绘制,而不是使用 bar。来自 MathWorks 的 This post 表示 bar()histc 选项已弃用。


使用histcounts代替histc:

xint=1/15;
edges_in=(0:xint:1);
[n,edges_out]=histcounts(data,edges_in);    % <-- changed
size(n)
size(edges_in)
size(edges_out)
bar(edges_out(1:end-1),n,'histc');       % <-- changed - last bin edge shouldn't be included
tit='p-values histogram';
htitle=title(tit);
set(htitle,'fontname','Calibri')
xlabel('p-values');
ylabel('Frequency');
axis([0 1 0 2500]);   % <-- added - but leave it off for debugging

根据 histc docs, "The last bin consists of the scalar value equal to last value in binranges." So the last bin is just 1.0. By contrast, with histcounts,"The last bin also includes the right bin edge, so that it contains X(i) if edges(end-1) ≤ X(i) ≤ edges(end)." 那应该做你想做的。

我在上面添加了一个 axis 来收紧情节,但为了调试而将其关闭,以便您可以查看最后一个柱状图是否仍然存在。

编辑 根据 histcounts docs,返回的向量比边缘向量少一个元素。如果是这种情况(根据编辑代码中的 size 打印输出),则应将其删除,这样 bar 就不会绘制该条。