根据百分比更改直方图的背景颜色

Change background color of histogram according to a percentage

我有一个直方图,我想为分布在直方图中 16.5% 到 83.5% 的点之间的背景着色。

我该怎么做?如何找到这些点?

数据在 file - 一列值中。

h = histogram( file, 50 );

详情请查看代码注释,基本上你可以使用 patch 来突出显示背景,并使用一些逻辑索引来查找哪些 bin 落在你的 16.5% - 83.5% 阈值内。

这使用 barhistcounts 来创建直方图而不是 histogram,因为您可以获得更多有用的输出并且我们需要在绘图之前进行中间步骤。

rng(0); % for repeatable random numbers
x = normrnd( 0, 1, 1000, 1 ) * 10; % Create data

% Get the histogram counts with 50 bins
[hc, edges] = histcounts( x, 50 );

% Lower and upper bounds we're interested in highlighting
region = [0.165, 0.835];
% Cumulative percentage across the bins
pct = cumsum( hc ) / sum( hc );
% Index to get which meet our bounds
idx = pct >= region(1) & pct <= region(2);

% Set up the plot
x = (edges(1:end-1)+edges(2:end))/2;
maxY = 1.1*max(hc);
n = nnz(idx);

% Plot
figure; hold on
patch( [x(idx),fliplr(x(idx))], [zeros(1,n),ones(1,n)]*maxY, 'y', 'edgecolor', 'none' );
bar( x, hc );
hold off
ylim( [0, maxY] );

结果:

只是想添加另一个变体。使用直方图属性和 prctile 查找限制:

data = randn(100000,1);

% Start with the original histogram
figure;
h=histogram(data,50);
% Find the bin edges you received.
be=h.BinEdges;

% Find the limits where your percentile limits lie
y=prctile(data,[16.5 83.5]);

% However, percentile limits will not generally concide with your bin-limits, so this must be fudged.

% Option A: Adjust be, to lie on the percentiles.
% DYI

% Option B: Adjust your limits for a pretty plot

% Find which be indicies are closest to the desired limits.
vals=y(:); 
rv=be(:)';
diffs=bsxfun(@minus,vals, rv); % Finds differences to all be for all vals.
[~,inds]=min(abs(diffs),[],2); % Finds the minimum ones.
vals=rv(inds);                 % Find values to use for the cutoff.

% Replace the original plot with the inner cut.
h1=histogram(data(data>vals(1) & data<vals(2)),'BinEdges',be);
hold on;
% Plot the data outside the limits.
h2=histogram(data(data<vals(1) | data>vals(2)),'BinEdges',be);

% Pretty colors have ensued. As per post, you can color the tails to
% something else
h2.FaceColor='white';

归功于 Tom R 对特定值的四舍五入: https://se.mathworks.com/matlabcentral/fileexchange/37674-roundtowardvec