This video is available to students only

Custom color scales

We learn how to create our own custom color scales and specify their color space.

Custom color scales#

Sometimes the built-in color scales don't cut it. Maybe you have specific colors that you want to work in, or you are going for a particular tone with your chart. No worries! We can make our own scales easily using d3-interpolate.

Let's say that we wanted to represent temperature values with a color, ranging from "cyan" to "red". There are several methods that we could use to interpolate between those two colors, including d3.interpolateRgb() and d3.interpolateHsl().

Let's make our own scale, running from "cyan" to "tomato" — all we need to do is pass our starting and ending color as separate parameters to d3.interpolateHcl().

We'll talk about the difference between the different color spaces (rgb, hsl, hcl) in the next section.

That will give us this scale:

color scales - our custom scale

Our code has been started off with a few different custom scales.

color scales - custom

If we open up the draw-scales.js file, we can test our own custom scales at the bottom. In the index.html file, we are importing other JavaScript files that list the built-in scale types and define a drawColorRange() function that creates an <svg> element with a linear-gradient.


This page is a preview of Fullstack D3 Masterclass

No discussions yet