DEV Community

Cover image for Interpolating colours within a range in D3.js
Aurelio
Aurelio

Posted on • Originally published at nobitagit.github.io

1 1

Interpolating colours within a range in D3.js

Colours can be a powerful visual hint in a data visualisation.
A good rule of thumb though is to use them sparingly, only when they add something meaningful to the chart and not just because they are pretty.

A good alternative to using many different colours is to use just a range of different shades of one or two colours across our entire dataset. This will highlight visually the differences in “weight” of each datapoint without distracting the user with an infinite rainbow of colours.
D3.js makes achieving this goal incredibly easy, allowing us to pass a colour codes to our ranges. We just need to pass the two colour codes we want to use as extremes and we will be good to go.

import { scaleLinear } from 'd3-scale';

const ourScale = scaleLinear()
  .domain([0, 100])
  .range([
     '#63a6d6', // <= lower bound of our color scale
     '#124488'  // <= upper bound of our color scale
  ]);
Enter fullscreen mode Exit fullscreen mode

D3.js will in turn interpolate the value we pass to our scale function to give us back the appropriate color code. Easy!
Here below a working JsFiddle to check how it works live.

Cover image is from Markus Spiske, check out his work here.

Originally published on my blog.

Billboard image

Deploy and scale your apps on AWS and GCP with a world class developer experience

Coherence makes it easy to set up and maintain cloud infrastructure. Harness the extensibility, compliance and cost efficiency of the cloud.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay