liveBook · Manning

Range()

As explained in D3.js in Action, Third Edition

range() is a D3 scale method that sets or retrieves the scale's output range.

range() sets a D3 scale’s output range: the screen values corresponding to the scale’s input domain. For a linear scale, pass an array containing the minimum and maximum outputs, such as pixel positions, widths, or colors. Calling the completed scale with a domain value returns the matching range value. section 3.4.1

Use range() according to the kind of output your visualization needs:

  • Set a continuous output with values such as [0, 450] when mapping quantitative data into available SVG space. section 3.4.2
  • Set a discrete output with a predefined list, such as colors corresponding to qualitative domain values. section 3.4.1
  • Use a range of [0, innerWidth] with a band scale to position categories such as years across a chart. section 5.1.1

Mapping bar-chart counts to pixels

const xScale = d3.scaleLinear() .domain([0, 1078]) .range([0, 450]); xScale(1078); // 450 xScale(414); // 172.82 svg.selectAll("rect") .data(data) .join("rect") .attr("width", d => xScale(d.count)); Here, range([0, 450]) keeps the bars within the available horizontal space while leaving room for labels. section 3.4.2

const myScale = d3.scaleLinear()
  .domain([0, 200])
  .range([0, 20]);

This compact listing shows range() chained after domain() to map input values from 0–200 into output values from 0–20. section 3.4.1

How D3.js in Action, Third Edition covers it

How deep it goes
Explains range() through chained scale setup and working chart code, stopping short of detailed scale-family internals.
Examples
Demonstrates pixel-mapped bar widths, color categories, and year positions for layered donut and stacked-bar charts.
What it assumes
Assumes basic JavaScript and SVG attributes while introducing domains, ranges, and continuous-versus-discrete mappings.
What you can do after
Apply it via D3 scales to translate data values into usable visualization dimensions and positions.
How it connects
Connects range() to domain(), d3.scaleLinear(), band scales, SVG attributes, and continuous or discrete data.

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.