Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 44 ยท Scales and Axes

Scales: Mapping Data to Pixels with scaleLinear

Understand D3 scales: domain and range, scaleLinear, invert, clamp, nice, ticks, rounding, reversed ranges for the y axis.

Data values and screen positions live in different worlds. A sales figure of 4,380 cannot be used as an x attribute, and a bar for 12 would be invisible next to 4,380. Scales are functions that translate from the data world (the domain) to the visual world (the range). They are the second most important idea in D3 after the data join, and they appear in every chart.

A scale is just a function

JavaScript
const x = d3.scaleLinear()
  .domain([0, 100])     // input values
  .range([0, 500]);     // output pixels

x(0);    // 0
x(50);   // 250
x(100);  // 500
x(120);  // 600  (extrapolates beyond the domain by default)

scaleLinear maps linearly: equal steps in the input give equal steps in the output. The rule is output = range0 + (value - domain0) / (domain1 - domain0) * (range1 - range0). D3 also lets you pass domain and range straight to the constructor: d3.scaleLinear([0, 100], [0, 500]).

A scale is a function

Domains from your data

Never type the domain by hand when it can come from the data. Pair a scale with d3.extent and d3.max (see Data Utilities):

JavaScript
const x = d3.scaleLinear()
  .domain(d3.extent(data, d => d.age))
  .range([0, innerWidth]);

const y = d3.scaleLinear()
  .domain([0, d3.max(data, d => d.income)])  // bars should start at zero
  .range([innerHeight, 0]);                   // flipped: SVG y grows down

For bar charts the value axis should start at zero, because bar length encodes the value; a truncated baseline exaggerates differences. For scatterplots and lines, using d3.extent is fine.

The y range is [innerHeight, 0] (largest pixel first). This inverts the scale so that big values end up near the top, because SVG's y axis points down.

nice, clamp, invert, ticks and round

A scale has several helper methods:

Method Purpose
.nice() Extends the domain to round numbers: [0.3, 97] becomes [0, 100]
.clamp(true) Output never leaves the range, even for out-of-domain input
.invert(pixel) The reverse mapping, from pixel back to data value (great for mouse positions)
.ticks(count) About count nice values in the domain, used for gridlines and axes
.tickFormat(count, spec) A formatter that matches those ticks
.rangeRound([a, b]) Same as .range but outputs integers, avoiding blurry lines
.unknown(value) What to return for undefined input (default undefined)
.copy() Creates an independent clone, e.g. to keep the original after zooming
nice, clamp, invert and ticks

nice() mutates the scale it is called on, which is why the example calls it on a copy(). Use nice when the axis should end on round numbers. Use invert for hover interaction: convert the mouse's pixel position back to a data value.

A real chart, no hard-coded math

Compare this chart with the very first one in this track, where bar heights were d.value * 1.8. The scales do that arithmetic and adapt automatically when the data or the size changes.

A bar chart driven by scales

The largest bar (5200) uses the full height because nice() rounds the domain up to 5500, so it fills about 95 percent. Change the data and the chart adapts.

Multi-segment (piecewise) scales

A domain and range can have more than two values. Then D3 maps piecewise: each interval of the domain maps to its own interval of the range. That is how you build a color scale that goes blue to white to red.

JavaScript
const color = d3.scaleLinear()
  .domain([-10, 0, 10])
  .range(["steelblue", "white", "tomato"]);

D3 detects that the range holds colors and interpolates between them (in RGB by default). You will see more of this in Color Scales.

Name your scales after the channel they control: x, y, r, color. If you have several x scales, use xTime, xBand. A tiny convention that makes long charts readable.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What are the domain and the range of a scale?

    A scale maps domain (data) to range (visual). The names are often confused, so remember: data in, pixels out.
  2. 2. Why does a vertical scale usually have range([innerHeight, 0])?

    Flipping the range puts big values at the top of the chart.
  3. 3. What does scale.invert(pixel) do?

    invert is the inverse function. It is commonly used to find the data value under the mouse.
  4. 4. When does .nice() help?

    nice() expands the domain ends to tick-friendly values such as 0 and 100.
  5. 5. Which is true of d3.scaleLinear().domain([0, 100]).range([0, 500])(120)?

    By default scales extrapolate. Call .clamp(true) to limit output to the range.

Summary

  • A scale is a function from domain (data) to range (pixels, colors, sizes).
  • Compute domains from the data with d3.extent or d3.max; start bar charts at zero.
  • Use nice, clamp, invert, ticks, rangeRound and copy for polish and interaction.
  • Flip the vertical range because SVG's y axis points down; multi-value domains create piecewise scales.

Next: Power, Log, Time and Other Continuous Scales