Skip to content

Instantly share code, notes, and snippets.

@swateek
Last active July 28, 2017 10:12
Show Gist options
  • Save swateek/d23ba23e99d0a434e236e48798601c48 to your computer and use it in GitHub Desktop.
Save swateek/d23ba23e99d0a434e236e48798601c48 to your computer and use it in GitHub Desktop.
Freedman-Diaconis thumb rule for number of bins of a histogram
// metric = array of real numbers (like > 100 or something)
// IQR = inter-quaartile-range
function numBins(metric, defaultBins) {
var h = binWidth(metric), ulim = Math.max.apply(Math, metric), llim = Math.min.apply(Math, metric);
if (h <= (ulim - llim) / metric.length) {
return defaultBins || 10; // Fix num bins if binWidth yields too small a value.
}
return Math.ceil((ulim - llim) / h);
}
function binWidth(metric) {
return 2 * iqr(metric) * Math.pow(metric.length, -1/3);
}
function iqr(metric) {
var sorted = metric.slice(0).sort(function (a, b) { return a - b; });
var q1 = sorted[Math.floor(sorted.length / 4)];
var q3 = sorted[Math.floor(sorted.length * 3 / 4)];
return q3-q1;
}
var metric = []
for(var i=0; i<1866; i++){
metric.push(i);
}
console.log(numBins(metric, 10));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment