Histogram: 'Greater than' bin

28 次查看(过去 30 天)
Simple question but I can't seem to find an answer: How do I add a bin to my histogram for the values outside of the visible range? Plotted automatically, the data below has values ranging from 0-200, the last 5 bins (100-200) have one point each. When I change the bin range to 0-100, those 5 bins are cut off. I want to take the points with values greater than the max(BinEdges) value, and have a bin labelled '>100' (populated dynamically as the bin edges are changed).
h=histogram(grains.area);
h.BinLimits=[0 100];
%Make range labels for bins
label = arrayfun(@(x,y) sprintf('%g - %g',x,y), ...
h.BinEdges(1:end-1), h.BinEdges(2:end), ...
'UniformOutput', false);
%label x axis with bin ranges
set(gca,'XTick',(h.BinEdges(1:end-1)+h.BinEdges(2:end))/2,...
'XTickLabel',label)
% get x position for bin count labels
xLblPos=h.BinEdges(1:end-1)+h.BinWidth/2;
%get y position
lift=max(h.Values)/20;
yLblPos=h.Values+lift;
%label each bar at top
cont=string(h.Values);
text(xLblPos,yLblPos,cont)

采纳的回答

Steven Lord
Steven Lord 2018-4-26
Add -Inf as the first element of the edges vector and/or Inf as the last element.
>> x = randn(1, 1e6);
>> h = histogram(x, [-Inf -2:0.25:2 Inf]);
>> tooSmallH = h.Values(1)
>> tooSmallX = nnz(x < -2)
>> tooLargeH = h.Values(end)
>> tooLargeX = nnz(x > 2)
The two variables whose names start with tooSmall should have the same value, as should the two variables whose names start with tooLarge.

更多回答(1 个)

Jessica Hiscocks
Jessica Hiscocks 2018-4-26
The above mostly answered the question, but didn't label the x axis correctly. It did help me find the answer though:
%plot histogram, covering data from -inf to +inf
%use user set max and mins
userMin=0;
userMax=100;
width=round((userMax-userMin)/6,0);
h = histogram(grains.area, [-Inf userMin:width:userMax Inf]);
%adjust the x axis limits to fit the data
if min(grains.area)<userMin
a=userMin-width;
else
a=userMin;
end
if max(grains.area)>userMax
b=userMax+width;
else
b=userMax;
end
ax=gca;
ax.XLim=[a b];
%Make range labels for numeric bins
label = arrayfun(@(x,y) sprintf('%g - %g',x,y), ...
h.BinEdges(1:end-1), h.BinEdges(2:end), ...
'UniformOutput', false);
%add label for 'over' bin
%label x axis with bin ranges
set(gca,'XTick',(h.BinEdges(1:end-1)+h.BinEdges(2:end))/2,...
'XTickLabel',label)
%manually adjust the xtics to have the even spacing (or else -inf and +inf
%plotted far off scale)
ax.XTick(1)=h.BinEdges(1)-width/2;
ax.XTick(end)=h.BinEdges(end-1)+width/2;
% get x position for bin count labels
xLblPos=ax.XTick;
%get y position
lift=max(h.Values)/20;
yLblPos=h.Values+lift;
%label each bar at top
cont=string(h.Values);
text(xLblPos,yLblPos,cont)

类别

Help CenterFile Exchange 中查找有关 Annotations 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by