This code creates a D3.js ordinal scale used to map...

June 27, 2025 at 10:03 PM

const color = d3.scaleOrdinal() .domain(data.map(d => d.range)) .range(d3.schemeCategory10);

This code creates a D3.js ordinal scale used to map categorical data (e.g., discrete values) to a predefined set of colors. Let's break it down step by step:

1. d3.scaleOrdinal()

  • Creates an ordinal scale in D3, which is used for mapping a set of discrete input values (categories) to discrete output values (e.g., colors).
  • This is particularly useful when you want to colorize data points based on categorical data.

2. .domain(data.map(d => d.range))

  • This defines the domain of the scale, which is the set of input values (categories).
  • data.map(d => d.range) extracts the range property from each object in the data array. The resulting array ([d.range, d.range, ...]) serves as the domain.
  • Essentially, the domain here is the list of unique categories (range values) in the data array.

3. .range(d3.schemeCategory10)

  • This defines the output range, i.e., the set of color values that correspond to the input categories.
  • d3.schemeCategory10 is a predefined color palette in D3.js with 10 distinct and visually distinguishable colors. If there are more than 10 categories in your domain, the colors will cycle through the palette.

Overall, what does this code do?

This code creates an ordinal color scale where:

  • The input domain is the set of range values from the data array (unique categories).
  • The output range is the d3.schemeCategory10 color palette.
  • You can then use this color scale (e.g., color(category)) to assign a consistent color to each category in domain.

Example use case:

If data looks like this:

const data = [
  { range: 'A', value: 10 },
  { range: 'B', value: 20 },
  { range: 'C', value: 30 },
];

The code will:

  • Set the domain as ['A', 'B', 'C'].
  • Map 'A', 'B', and 'C' to specific colors from d3.schemeCategory10.

You can then use the resulting color scale like this:

console.log(color('A')); // Outputs a color for 'A' from d3.schemeCategory10
console.log(color('B')); // Outputs a color for 'B'
Generate your own explanations
Download our vscode extension
Read other generated explanations

Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node