Contents

How to Manage Ordinal Scales in D3.js?

What are ordinal scales? How to use them in D3.js? This type of scale is a bit different than these we saw before (linear, logarithmic, time).

When do we need ordinal scales?

Sometimes we want to use scale to work with discrete data like a collection of categories instead of continuous data.

For this, we need to use and ordinal scale. We only use this type of scale when we want to associate different categories with different colors. It can also be used to associate any two strings with each other.

How it works?

For ordinal scales, the domain and the range are arrays of values and the scale will provide a mapping between them base on their position in the array.

As you can imagine, the syntax is a little bit different of linear scales. We need to define an array of strings to the domain method. Let’s do it.

1
2
const ordinalscale = d3.scaleOrdinal()
ordinalscale.domain(["France", "England", "Spain", "Germany", "Italy"])

You can define a range array by yourself like this:

ordianalscale.range(["RED", "ORANGE","YELLOW","GREEN","BLUE"])

Or you can do better with schemeCategory that is provided by D3 and allows you to use color schemes:

ordianalscale.range(d3.schemeCategory10)

And that’s it! You can now display different country with different colors. The scale will automatically map a country to a color using schemeCategory. If you want to change the scheme you can have a quick look at this git repository: https://github.com/d3/d3-scale-chromatic

I hope you enjoyed this post. Do not hesitate to ask your questions in DM. See you!