Calculate number of bins for histogram

Automatically calculates the 'best' number of bins for a histogram.


Updated 24 Oct 2008

View License

Two files are included:
CALCNBINS, which calculates the "ideal" number of bins to use in a histogram, using three possible methods. (Freedman-Diaconis', Scott's and Sturges' methods.)

HISTX is a wrapper for Matlab's own histogram function HIST, that uses CALCNBINS to choose the number of bins if none is provided.

y = randn(10000,1);
nb = calcnbins(y, 'all')
% nb =
% fd: 57
% scott: 44
% sturges: 15
calcnbins(y) %Uses the middle value from the above
% ans =
% 44
calcnbins(y, 'fd') % Choose your method
% ans =
% 57
histx(y) %Plots a histogram using middle method
histx(y, 'all') %Plots 3 histograms, using each method

Cite As

Richie Cotton (2023). Calculate number of bins for histogram (, MATLAB Central File Exchange. Retrieved .

MATLAB Release Compatibility
Created with R2008a
Compatible with any release
Platform Compatibility
Windows macOS Linux

Community Treasure Hunt

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

Start Hunting!
Version Published Release Notes

NaN values are now consistently ignored in calcnbins.

Bug fix