1
d3.layout.histogram = function() {
4
ranger = d3_layout_histogramRange,
5
binner = d3_layout_histogramBinSturges;
7
function histogram(data, i) {
9
values = data.map(valuer, this),
10
range = ranger.call(this, values, i),
11
thresholds = binner.call(this, range, values, i),
15
m = thresholds.length - 1,
16
k = frequency ? 1 : 1 / n,
19
// Initialize the bins.
22
bin.dx = thresholds[i + 1] - (bin.x = thresholds[i]);
26
// Fill the bins, ignoring values outside the range.
28
i = -1; while(++i < n) {
30
if ((x >= range[0]) && (x <= range[1])) {
31
bin = bins[d3.bisect(thresholds, x, 1, m) - 1];
41
// Specifies how to extract a value from the associated data. The default
42
// value function is `Number`, which is equivalent to the identity function.
43
histogram.value = function(x) {
44
if (!arguments.length) return valuer;
49
// Specifies the range of the histogram. Values outside the specified range
50
// will be ignored. The argument `x` may be specified either as a two-element
51
// array representing the minimum and maximum value of the range, or as a
52
// function that returns the range given the array of values and the current
53
// index `i`. The default range is the extent (minimum and maximum) of the
55
histogram.range = function(x) {
56
if (!arguments.length) return ranger;
57
ranger = d3_functor(x);
61
// Specifies how to bin values in the histogram. The argument `x` may be
62
// specified as a number, in which case the range of values will be split
63
// uniformly into the given number of bins. Or, `x` may be an array of
64
// threshold values, defining the bins; the specified array must contain the
65
// rightmost (upper) value, thus specifying n + 1 values for n bins. Or, `x`
66
// may be a function which is evaluated, being passed the range, the array of
67
// values, and the current index `i`, returning an array of thresholds. The
68
// default bin function will divide the values into uniform bins using
70
histogram.bins = function(x) {
71
if (!arguments.length) return binner;
72
binner = typeof x === "number"
73
? function(range) { return d3_layout_histogramBinFixed(range, x); }
78
// Specifies whether the histogram's `y` value is a count (frequency) or a
79
// probability (density). The default value is true.
80
histogram.frequency = function(x) {
81
if (!arguments.length) return frequency;
89
function d3_layout_histogramBinSturges(range, values) {
90
return d3_layout_histogramBinFixed(range, Math.ceil(Math.log(values.length) / Math.LN2 + 1));
93
function d3_layout_histogramBinFixed(range, n) {
96
m = (range[1] - b) / n,
98
while (++x <= n) f[x] = m * x + b;
102
function d3_layout_histogramRange(values) {
103
return [d3.min(values), d3.max(values)];