首页 > 解决方案 > 根据百分比更改直方图的背景颜色

问题描述

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

我怎样才能做到这一点?如何找到这些点?

数据在file- 一列值中。

h = histogram( file, 50 );

标签: matlabhistogrammatlab-figure

解决方案


就像添加另一个变体一样。使用直方图属性和 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/376​​74-roundtowardvec


推荐阅读