D3.js Color Scales — Mapping Data to Color
In this tutorial, you will learn about D3.js Color Scales. We cover key concepts, practical examples, and best practices to help you master this topic.
D3.js color scales map numerical or categorical data to visual color encodings using built-in schemes and custom interpolation functions.
What You'll Learn
By the end of this guide, you will use sequential, diverging, and ordinal color scales, apply d3-scale-chromatic color schemes, interpolate colors, create custom palettes, and build a choropleth map.
Sequential Color Scale
var scale = d3.scaleSequential(d3.interpolateBlues)
.domain([0, 100]);
console.log(scale(0)); // rgb(247, 251, 255)
console.log(scale(50)); // rgb(145, 188, 226)
console.log(scale(100)); // rgb(8, 48, 107)
Diverging Color Scale
var scale = d3.scaleDiverging(d3.interpolateRdBu)
.domain([-10, 0, 10]);
console.log(scale(-10)); // rgb(178, 24, 43)
console.log(scale(0)); // rgb(247, 247, 247)
console.log(scale(10)); // rgb(33, 102, 172)
Categorical (Ordinal) Scale
var scale = d3.scaleOrdinal(d3.schemeCategory10)
.domain(['A', 'B', 'C', 'D', 'E']);
console.log(scale('A')); // #1f77b4
console.log(scale('B')); // #ff7f0e
Custom Color Interpolation
var custom = d3.scaleSequential(function(t) {
return d3.interpolateRgb('white', '#ff6b35')(t);
}).domain([0, 100]);
Log Color Scale
var scale = d3.scaleSequentialLog(d3.interpolateViridis)
.domain([1, 1000]);
Common Mistakes
1. Using Wrong Scale Type
Sequential needs a continuous domain. Ordinal needs categorical data. Using the wrong type produces confusing results.
2. Not Setting Domain Correctly
Color scales clip values outside the domain. Set domain to match data's min and max.
3. Ignoring Color Blindness
Red-green schemes are hard for color-blind viewers. Use ColorBrewer schemes like RdYlBu or Viridis.
4. Too Many Categories in Ordinal Scale
d3.schemeCategory10 has 10 colors. With more categories, colors repeat. Use schemeSet3 (12 colors) or custom.
5. Using Interpolation on Wrong ColorSpace
d3.interpolateRgb uses RGB. Use d3.interpolateLab or d3.interpolateHcl for perceptually uniform transitions.
Practice Questions
Q1: What is the difference between d3.interpolateViridis and d3.interpolateBlues? A: Viridis is perceptually uniform and multi-hue. Blues is a single-hue sequential scheme.
Q2: How many colors does d3.schemeCategory10 provide? A: 10 distinct colors for categorical data.
Q3: What happens if input data is outside the domain? A: Values below domain min get the minimum color; values above get the maximum color (clamping).
Q4: How do you reverse a color scale?
A: Reverse the domain: .domain([max, min]) instead of [min, max].
Q5: What is d3.interpolateRdBu good for? A: Diverging data with a meaningful mid-point like zero or average.
Challenge: Build a choropleth of US states with a diverging color scale. Use real GDP per capita data. Show state name on hover.
FAQ
Try It Yourself
Build a scatter plot with color mapped to a third dimension.
<!DOCTYPE html>
<html>
<head>
<title>Color Scales Demo</title>
<style>
body { font-family: sans-serif; padding: 20px; background: #f5f5f5; }
svg { background: white; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
.dot { stroke: #fff; stroke-width: 1; }
#legend { margin-top: 10px; }
</style>
</head>
<body>
<h2>Color by Value</h2>
<svg width="600" height="400" id="chart"></svg>
<div id="legend">Blue (low) to Red (high)</div>
<script src="https://d3js.org/d3.v7.min.js"></script>
<script>
var width = 600, height = 400;
var svg = d3.select('#chart');
var data = d3.range(80).map(function() {
return {
x: Math.random() * width,
y: Math.random() * height,
value: Math.random() * 100
};
});
var colorScale = d3.scaleSequential(d3.interpolateRdYlBu)
.domain([0, 100]);
svg.selectAll('circle')
.data(data).enter()
.append('circle').attr('class', 'dot')
.attr('cx', function(d) { return d.x; })
.attr('cy', function(d) { return d.y; })
.attr('r', function() { return 3 + Math.random() * 7; })
.attr('fill', function(d) { return colorScale(d.value); });
</script>
</body>
</html>
What's Next
Explore SVG shape generators.
Shapes — SVG shape generators. Project — Data dashboard project.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro