Scales
🎯 Introduction
So far, bar heights have equaled their values: 120 produces a 120px bar. But a sales value of 12000 would produce a bar too tall for the screen. This article introduces D3 scales, which convert data values into pixel values automatically.
🧱 What is a scale?
A scale is a function: pass in a data value and receive a pixel value.
It works like a map where 1 centimeter represents 10 kilometers. Rather than measuring the Earth with a tape measure, you use the scale to draw distances on paper.
To create a scale, specify two intervals:
const yScale = d3
.scaleLinear()
.domain([0, 10000]) // Input values: 0 to 10000
.range([300, 0]); // Output pixels: 300 to 0
domain: The data interval (input).range: The corresponding pixel interval (output).
Once created, the scale is an ordinary function. Call it to see the conversion:
| Call | Meaning | Result |
|---|---|---|
yScale(0) | Minimum value | 300 (bottom) |
yScale(5000) | Midpoint value | 150 (middle) |
yScale(10000) | Maximum value | 0 (top) |
The value 5000 is halfway between 0 and 10000, and 150 is halfway between 300 and 0. This proportional mapping explains the name scaleLinear.
Move the slider to change the value. The red line connects the input on the data ruler to the output on the pixel ruler: exactly the conversion performed by yScale.
[300, 0]. SVG y coordinates increase downward: 0 is the top and 300 the bottom. Larger values need higher bars, so they map to smaller y coordinates. Using [0, 300] turns the chart upside down, a common beginner mistake.🧱 scaleLinear: calculate the domain from data
Real data varies, so hard-coding [0, 10000] is rarely appropriate. Use d3.max to find the maximum:
const data = [120, 200, 150, 80, 70];
const yScale = d3
.scaleLinear()
.domain([0, d3.max(data)]) // d3.max returns 200
.range([300, 0])
.nice();
Two useful helpers:
d3.max(data)returns the largest array value.d3.minprovides the corresponding minimum..nice()rounds domain boundaries to convenient values. For a maximum of 198, the domain can become[0, 200], producing tidy ticks such as 0, 50, and 100 rather than 0, 39.6, and 79.2.
🧱 scaleBand: allocate space to categories
A bar chart's horizontal axis often contains categories, such as Monday and Tuesday, rather than numbers. Use scaleBand to divide the available width into evenly spaced bands.
const xScale = d3
.scaleBand()
.domain(['Mon', 'Tue', 'Wed', 'Thu', 'Fri'])
.range([0, 260])
.padding(0.2); // Set padding to 20% of the step
For 260px and five categories, the step is 50px. With padding(0.2), 20% of that step is reserved for spacing, leaving a 40px bar width:
| Call | Result | Meaning |
|---|---|---|
xScale('Mon') | 10 | Start of Monday's bar |
xScale('Wed') | 110 | Start of Wednesday's bar |
xScale.bandwidth() | 40 | Width of each bar |
Instead of manually calculating positions with i * 60 and setting a width of 40, use xScale(d.day) and xScale.bandwidth(). Changes to data or chart width no longer require manual recalculation.
Move the slider to change padding and compare the steps (dashed boxes) with the solid bar widths:
🧱 scaleTime: work with dates
For a date-based horizontal axis, use scaleTime with Date objects in the domain:
const xScale = d3
.scaleTime()
.domain([new Date('2026-01-01'), new Date('2026-01-07')])
.range([0, 300]);
xScale(new Date('2026-01-04')); // 150: January 4 is halfway through the interval
Time scales are often used with axes. D3 automatically selects suitable daily ticks for this interval:
⚖️ Choosing a scale
| Scale | Domain type | Typical use |
|---|---|---|
scaleLinear | Continuous numbers | Numeric y axis |
scaleBand | Discrete categories | Bar chart x axis |
scaleTime | Date objects | Time-series x axis |
Remember: Linear for numbers, Band for categories, Time for dates.
❓ Questions and answers
Q1: What happens if I reverse the range?
The scale still works, but the mapping reverses, so larger values can produce shorter bars. If the chart looks upside down, check whether the range should be [height, 0].
Q2: What values can scaleBand padding take?
Use a fraction between 0 and 1 to control spacing relative to each step. Values from 0.1 to 0.3 are common; excessive padding makes bars too narrow.
Q3: How do I use d3.max with an array of objects?
Pass an accessor as the second argument: d3.max(data, d => d.value).
Q4: Can scales map values to colors?
Yes. Set the range to colors, such as .range(['#e0f3ff', '#08589e']). Larger values then produce darker colors, a common technique in heatmaps.
🧪 Exercise
Create two scales for the data below and verify the results in the console:
- Create an x scale with
scaleBand, the five subjects as its domain, and[0, 400]as its range. - Create a y scale with
scaleLinear, a domain from 0 to the highest score, and a range of[300, 0]. - Print
xScale('Math'),xScale.bandwidth(), andyScale(88)and check the results.
const data = [
{ subject: 'Chinese', score: 80 },
{ subject: 'Math', score: 95 },
{ subject: 'English', score: 88 },
{ subject: 'Physics', score: 72 },
{ subject: 'Chemistry', score: 90 },
];
// Write your code here
🎉 You now understand scales, a core building block! Next, we will combine them with axes to create a complete bar chart with ticks.
