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
