liveBook · Manning

D3.bin()

As explained in D3.js in Action, Third Edition

d3.bin() is a D3-array function that groups numeric values into bins according to a configured domain, thresholds, and value accessor.

d3.bin() groups numeric data into bins so you can see a distribution. Each bin covers an interval along an axis and contains the data points in that interval. The result is an array of bins: each bin is itself an array, with lower and upper boundaries available as x0 and x1. section 6.1 section 6.6

Bin salary records

If each data point is an object with a salary field, tell the bin generator which value to use: const binGenerator = d3.bin() .value(d => d.salary); const bins = binGenerator(data); Now each bin contains the original records whose salaries fall within its boundaries. bins can be used as the data for a chart. section 6.1

Figure 6.3 In the multidimensional array returned by the bin generator, each bin is an array containing data points. In this figure, the data points, consisting of JavaScript objects, are represented by {...} for conciseness. A bin’s lower and upper limits are accessible under the keys x0 and x1.
figure

See how the returned array holds records inside bins, with x0 and x1 marking each bin’s limits. section 6.1

For a histogram, bind the bins to rectangles. A bin’s length gives the number of data points to represent; x0 and x1 locate its edges. To compare two groups in a pyramid chart, generate separate salary bins for each group, then place their bars back-to-back. section 6.6 section 6.3

Reuse bins in a violin plot

When salaries are already an array of numbers, no salary accessor is needed: role.bins = d3.bin()(role.salaries); For each role, the bin lengths can set the width of a histogram bar or a curved violin shape. The bin boundaries position that shape along the salary axis. section 6.5

How D3.js in Action, Third Edition covers it

How deep it goes
Shows a salary value accessor, the returned bin arrays and boundaries, and how bin lengths and boundaries drive chart geometry.
Examples
Uses survey salary records for binning, separate gender distributions for a pyramid chart, and role-specific salaries for violin plots.
What it assumes
Assumes basic JavaScript data handling and chart rectangles while demonstrating how to create bins with a salary accessor.
What you can do after
Apply it via d3.bin() to prepare salary data for histograms, side-by-side distribution comparisons, and violin plots.
How it connects
Connects binning to histograms, pyramid charts, violin plots, SVG data binding, and linear scales.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of D3.js in Action, Third Edition. The section links point to the parts of the book it draws on.