liveBook · Manning

Band scale

As explained in D3.js in Action, Third Edition

scaleBand() is a D3 scale function that maps discrete categorical input values to continuous numeric positions or bands.

A band scale maps discrete categories to continuous positions within a visual range. In D3, d3.scaleBand() is especially useful for distributing bars across the available space in a bar chart. section 3.4.1 section 3.6

Build a vertical band scale and use it to position and size rectangles:

  • Create the scale with d3.scaleBand(). section 3.4.3
  • Set the domain to the categorical values, such as data.map(d => d.technology). section 3.4.3
  • Set the range to the available screen space, such as [0, 700] for an SVG’s vertical extent. section 3.4.3
  • Pass each bound category to the scale when setting a rectangle’s position: .attr("y", d => yScale(d.technology)). section 3.4.3
  • Use yScale.bandwidth() for the rectangle height; add paddingInner(0.2) when separation between bands is needed. section 3.4.3

Positioning technology bars

const yScale = d3.scaleBand() .domain(data.map(d => d.technology)) .range([0, 700]); svg.selectAll("rect") .data(data) .join("rect") .attr("y", d => yScale(d.technology)) .attr("height", yScale.bandwidth()); For this scale, yScale("Excel") returns 0, while yScale("D3.js") returns the position of the D3 bar. The scale determines placement and bandwidth determines thickness. section 3.4.3

Sharing a scale across charts

A band scale can also place chart groups horizontally. Set its domain from loaded years, use [0, innerWidth] as the range, and translate each donut group with xScale(year). The same scale can later align a stacked bar chart with the donut charts. section 5.1.1

Figure 3.29 How the band scale distributes the list of technologies within the available vertical space
figure

Compare bars distributed without padding and with padding to see how the band scale divides available space. section 3.4.3

How D3.js in Action, Third Edition covers it

How deep it goes
Explains domain, range, bandwidth, padding, and SVG integration, but defers broader scale selection details.
Examples
Uses technology bars, year-positioned donut charts, padding comparisons, and mobile bar-chart orientation.
What it assumes
Assumes basic JavaScript map(), data binding, SVG elements, and loaded datasets while reinforcing scale-based positioning.
What you can do after
Build it from scratch by mapping categories to SVG positions, bar thicknesses, group translations, and responsive chart layouts.
How it connects
Connects band scales with D3 scales, data binding, SVG rectangles, bar charts, axes, and responsive visualization.

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.