如何从不同大小的矩阵生成堆叠直方图?

How to generate a stacked histogram from different sized matrices?

我有两个不同大小的矩阵,一个是3000 x 1,另一个是6000 x 1。我想根据这些矩阵绘制堆叠直方图。这是我到目前为止尝试过的代码:

hist(S1,20);
hold on
hist(S,20)
h = findobj(gca,'Type','patch');
display(h) 
set(h(1),'FaceColor',[0 0 0],'EdgeColor',[1 1 1],'facealpha',1.0);
set(h(2),'FaceColor',[1 1 1],'EdgeColor',[0 0 0],'facealpha',.3);

最后的情节是这样的,没有堆叠:

MATLAB 的 bar method has a 'stacked' option. It's irrelevant, if your arrays have different sizes or varying value ranges, as long as the histograms you create have the same x-values. You can achieve that by properly setting the xbins 参数。

这是一个小例子:

S1 = randi([-8 8], 30, 1);
S2 = randi([-10 10], 60, 1);

hist_range = -10:10;

h1 = hist(S1, hist_range)
h2 = hist(S2, hist_range)

figure(1);
bar(hist_range, [h1(:), h2(:)], 'stacked')
xlim([-11 11]);
legend('h1', 'h2');

示例输出(Octave 5.1.0,代码也使用 MATLAB Online 测试):

h1 =
   0   0   2   2   3   1   1   0   3   1   3   2   2   0   1   2   3   1   3   0   0

h2 =
   2   2   2   0   4   5   0   2   3   2   5   3   0   6   3   6   2   5   1   5   2

希望对您有所帮助!