Skip to content

D3.js - Colors API

Color is a vital aspect of data visualization. D3’s d3-color module provides robust tools for parsing, converting, and manipulating colors. It supports various color spaces like RGB, HSL, Lab, HCL, and Cubehelix.

Colors can be specified in CSS in several ways: by name (e.g., “steelblue”), as RGB values (e.g., rgb(70, 130, 180)), hexadecimal values (e.g., #4682b4), HSL values (e.g., hsl(207, 44%, 49%)), etc. D3 can parse most CSS color specifiers.

The d3-color module is part of the main D3.js bundle. If using modules separately, you can install d3-color.

<!-- Option 1: Include the full D3 library -->
<script src="https://d3js.org/d3.v7.min.js"></script>
<!-- Option 2: Include the standalone d3-color module -->
<!-- <script src="https://d3js.org/d3-color.v3.min.js"></script> -->
<script>
// Example usage:
// const myColor = d3.color("tomato");
// console.log(myColor.rgb().toString()); // "rgb(255, 99, 71)"
</script>

The d3.color(specifier) function is the primary way to parse a color string. It returns a color object, which has methods for conversion and manipulation.

const c = d3.color("steelblue"); // Parses "steelblue"
// Get RGB components
console.log(`R: ${c.r}, G: ${c.g}, B: ${c.b}`); // R: 70, G: 130, B: 180
// Get opacity
console.log(`Opacity: ${c.opacity}`); // Opacity: 1
// Convert to HSL
const hslColor = c.hsl();
console.log(`H: ${hslColor.h}, S: ${hslColor.s}, L: ${hslColor.l}`);
// Manipulate color (returns a new color object)
const brighterColor = c.brighter(1.5);
console.log(`Brighter: ${brighterColor.formatHex()}`); // Brighter: #6ba5d8 (example)
const darkerColor = c.darker(0.7);
console.log(`Darker: ${darkerColor.formatHex()}`); // Darker: #325a7f (example)
// Change opacity
c.opacity = 0.5;
console.log(`Faded: ${c.toString()}`); // Faded: rgba(70, 130, 180, 0.5)

Key methods related to d3-color:

  • d3.color(specifier) − Parses the CSS color specifier (e.g., name, hex, rgb(), hsl()) and returns a color object (usually an instance of d3.rgb or d3.hsl). Returns null if the specifier is invalid.
  • color.r, color.g, color.b − For RGB color objects, these properties hold the red, green, and blue channel values (0-255).
  • color.h, color.s, color.l − For HSL, HCL, or Cubehelix color objects, these properties represent hue, saturation, and lightness/luminance, respectively. Ranges vary by color space.
  • color.opacity − The opacity value, ranging from 0 (fully transparent) to 1 (fully opaque).
  • color.rgb() − Returns an RGB representation of the color. All color objects have this method.
  • color.hsl() − Returns an HSL representation of the color.
  • color.lab() − Returns a Lab color space representation.
  • color.hcl() − Returns an HCL (LChuv) color space representation.
  • color.cubehelix() − Returns a Cubehelix color space representation.
  • color.brighter([k]) − Returns a new, brighter color. k (default 1) is the brightening factor.
  • color.darker([k]) − Returns a new, darker color. k (default 1) is the darkening factor.
  • color.displayable() − Returns true if the color is displayable (i.e., RGB channels are within [0, 255] and opacity is [0, 1]).
  • color.formatHex() − Returns the RGB hexadecimal string (e.g., “#RRGGBB”).
  • color.formatHsl() − Returns the HSL string representation (e.g., “hsl(H,S%,L%)”).
  • color.formatRgb() − Returns the RGB string representation (e.g., “rgb(R,G,B)”).
  • color.toString() − Equivalent to formatRgb() or formatHsl(), depending on the color object type. For opacity < 1, it usually returns an rgba() or hsla() string.
  • d3.rgb(r, g, b[, opacity]) or d3.rgb(specifier) − Constructs a new RGB color. Can also parse a specifier.
  • d3.hsl(h, s, l[, opacity]) or d3.hsl(specifier) − Constructs a new HSL color.
  • d3.lab(l, a, b[, opacity]) or d3.lab(specifier) − Constructs a new Lab color.
  • d3.hcl(h, c, l[, opacity]) or d3.hcl(specifier) − Constructs a new HCL color.
  • d3.cubehelix(h, s, l[, opacity]) or d3.cubehelix(specifier) − Constructs a new Cubehelix color.

Different color spaces have different perceptual properties. HSL is intuitive for hue rotation. Lab and HCL are designed to be perceptually uniform, meaning a change in color value corresponds to a similar perceived change in color. This is useful for creating color scales for data.

const baseColor = d3.hcl("purple");
console.log("Base HCL:", baseColor.toString());
// Modify luminance in HCL (often better for perceived brightness changes)
const lighterHCL = d3.hcl(baseColor.h, baseColor.c, baseColor.l + 20, baseColor.opacity);
console.log("Lighter HCL:", lighterHCL.rgb().toString()); // Convert back to RGB for display
const saturatedHCL = d3.hcl(baseColor.h, baseColor.c + 30, baseColor.l, baseColor.opacity);
console.log("Saturated HCL:", saturatedHCL.rgb().toString());
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>D3 Color API Examples</title>
<script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
<h3>Check the browser console for D3 Color API outputs.</h3>
<script>
console.log("--- D3 Color Examples ---");
const color1 = d3.color("coral");
console.log('Original (coral):', color1.toString(), color1);
console.log('Is displayable?', color1.displayable());
console.log('Hex format:', color1.formatHex());
const color2 = d3.rgb(50, 150, 200, 0.8);
console.log('\nRGB color:', color2.toString(), color2);
console.log('Brighter version:', color2.brighter(2).toString());
const color3 = d3.hsl("green");
console.log('\nHSL color (green):', color3.toString(), color3);
color3.h += 60; // Shift hue
color3.s -= 0.2; // Desaturate
console.log('Modified HSL:', color3.toString());
const labColor = d3.lab("navy");
console.log('\nLab color (navy):', labColor.toString(), labColor);
// Lab values: l (lightness), a (green-red axis), b (blue-yellow axis)
console.log(`Lab values: l=${labColor.l.toFixed(2)}, a=${labColor.a.toFixed(2)}, b=${labColor.b.toFixed(2)}`);
const cubehelixColor = d3.cubehelix(300, 0.5, 0.5); // h, s, l for Cubehelix
console.log('\nCubehelix color:', cubehelixColor.toString(), cubehelixColor);
</script>
</body>
</html>

The d3-color module is used for:

  • Defining static colors for chart elements.
  • Programmatically adjusting colors (e.g., for hover effects, highlighting).
  • Creating color scales by interpolating between colors (often in conjunction with d3-interpolate and d3-scale).
  • Converting colors between different color spaces for specific visual effects or perceptual uniformity.

For creating entire color schemes (e.g., categorical, sequential, diverging), D3 provides the d3-scale-chromatic module, which offers a wide range of predefined, perceptually-tested color palettes. These palettes often use colors defined and manipulated via d3-color principles.

For more in-depth information, visit the d3-color documentation.