我有一个直方图,我想为直方图中分布的点的16.5%和83.5%之间的背景上色。
我该怎么做?如何找到这些点?
数据位于file
中-一列值。
h = histogram( file, 50 );
答案 0 :(得分:6)
就像添加另一个变体一样。使用直方图属性和实用性来找到限制:
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
答案 1 :(得分:5)
请查看代码注释以获取详细信息,基本上,您可以使用patch
突出显示背景,并使用一些逻辑索引来查找哪些垃圾箱落在您的16.5%-83.5%阈值之内。
这将使用bar
和histcounts
而不是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] );
结果: