liveBook · Manning

Color scale

As explained in D3.js in Action, Third Edition

A color gradient is a gradual transition between colors across a graphical region or element.

A color scale maps data values to colors so a visualization can distinguish categories or communicate numerical differences. In D3, ordinal scales assign discrete colors to discrete labels, while sequential scales convert continuous values into a progression of colors. section 5.1.3 section 13.2.3

Choose the scale type that matches the data:

  • Use an ordinal scale when categories such as music formats or language families each need a specific color. section 5.1.3 section 11.2.2
  • Use a sequential scale when increasing values should produce increasingly different colors, such as Nobel laureate counts on a map. section 13.2.3
  • Set sensible numeric bounds: capping the upper domain can preserve visible differences when one outlier would flatten most colors. section 13.2.3
  • Keep zero or missing values visibly distinct when necessary; the map leaves countries without laureates white. section 13.2.3

Coloring a circle pack

Create an ordinal scale from language-family labels and colors, then apply it to depth-one circles. Derive a paler parent color for depth-two branches and leave leaf nodes white.

Coloring a choropleth map

Initialize d3.scaleSequential with d3.interpolateYlGnBu and domain [1, 100]. Apply the returned color to countries with laureates, while assigning a pale fill to countries with none. Add a tooltip when exact values matter, because color alone communicates comparison better than precise counts.

Listing 13.3 Declaring the color scale (scales.js)
import { scaleSequential } from "d3-scale";
import { interpolateYlGnBu } from "d3-scale-chromatic";

export const countryColorScale = scaleSequential(interpolateYlGnBu)
  .domain([1, 100]);

Inspect the complete sequential-scale declaration used to turn Nobel laureate counts into map colors. section 13.2.3

How D3.js in Action, Third Edition covers it

How deep it goes
Explains ordinal and sequential domains, implementation, outlier handling, and application to SVG marks.
Examples
Uses donut charts, language-family circle packs, and Nobel-laureate choropleth maps with tooltips.
What it assumes
Assumes JavaScript data binding and SVG mark creation while introducing scale domains, ranges, and interpolators through projects.
What you can do after
Build it from scratch with D3 by declaring domains, choosing ranges or interpolators, and applying colors to marks.
How it connects
Connects ordinal scale, sequential scale, D3, SVG, Canvas, choropleth map, and legends.

Also explained in

Compare how 5 books explain color scale →

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.