Search⌘ K
AI Features

Using Ordinal Scales

Explore how to define and use ordinal scales in D3.js to assign colors to categories such as age groups. Understand generating color ranges using chromatic scales, quantizing colors uniformly, and applying these scales to chart elements for effective data representation.

We'll cover the following...

We are going to jump straight into it. Under the scales section, we are going to define a variable called colorScale. Its value will be the d3.scaleOrdinal() function.

Javascript (babel-node)
const colorScale = d3.scaleOrdinal()
.domain(dataset.map(element => element.name))
.range()

For the domain, unlike other scales, we can not provide a range of values. Instead, we need to provide a full list of values that should be transformed. In our case, we are going to provide a list of age groups. We are not going to pass in the entire data array. We will generate a new array with the age groups.

We can generate a new array based on a previous array by calling the map() function. Inside the domain() function, we are calling the dataset.map() function. ...