Colour scales in D3 Version 5
Over the past versions in D3.js there have been a number of changes to how you can get a colour scale to use with your charting. This blog post explores what is available and how to use it. This blog post applies to D3.js version 5.
Colour scales in D3.js version 5
The default colour scales provided in D3.js vesion 5 are provided by the d3-scale-chromatic module which is included in the default d3 redistributable.
There are two types of colour scales provided by this module. The first set is a number of arrays containing some pre-picked colours. These have been chosen to fit together can easily be used for diagrams. The second set is an interpolation scheme allowing for a continuous colour set. These can produce a much larger range of colours but when used for a large number of colours these will be less distinct.
How to use D3.js colour schemes
The D3.js colour schemes are a given set of themed colours for use of data visualization. Using the d3.scaleOrdinal
you can access these using a function call passing in the index of the colour you want to use.
As an example, using the d3.schemeCategory10
set of colours:
var colourSet = d3.scaleOrdinal(d3.schemeCategory10); var firstColour = colourSet(0); var secondColour= colourSet(1);
Using the generated function, colourSet
, you can pass in your series index to produce a different colour for each data point.
The full list of D3.js colour schemes is available on the GitHub page.
How to use D3.js colour interpolation
The colour interpolation functions allow creating a large range of colours given a value from 0 to 1. Using the d3.scaleSequential
you can map your discrete scale of values to the continuous one, providing a number of colours from the scale.
Unlike the colour schemes, using interpolation you are able to produce any number of necessary colours. An example is below:
var interpolateViridisColours = d3.scaleSequential(d3.interpolateViridis).domain([0, 149]); var firstColour = interpolateViridisColours(0); var secondColour = interpolateViridisColours(1); var onehundredAndFiftiethColour = interpolateViridisColours(149);
Here we are first using the d3.scaleSequential
function to scale the interpolation function, then calling domain on it to scale it to expect between 0 and 149 (giving us 150 colours). This can be done for any range of colours.
It is important to note that the larger the domain you specify, the less different the colours will be.
Summary of colour schemes
Using both d3.scaleSequential
and d3.scaleOrdinal
we can create a function which will take our series index and produce a colour. This means you can easily swap different colouring function without changing large parts of your code. This feature reduces code coupling and therefore improves ease of use.