Color Theory and D3 Scales

CS-GY 6313 - Fall 2026

Claudio Silva

NYU Tandon School of Engineering

2026-10-02

Color Theory and D3 Scales

Today’s Journey

Biology/PhysicsPerception TheoryDesign PrinciplesD3 ImplementationBest Practices


Part 1: Color Theory

  • Physics and physiology of color
  • How humans perceive color
  • Color spaces and models
  • Perceptual principles

Part 2: D3 Implementation

  • Color scales in D3
  • Sequential, diverging, categorical
  • Interpolation methods
  • Accessibility and best practices

Color in Nature

The Visible Spectrum

  • Humans perceive wavelengths from roughly 390 to 700 nm
  • Shorter (UV) is scattered by the atmosphere; longer (IR) is absorbed by water
  • Peak sensitivity near 555 nm, the peak of sunlight at the surface
  • Every colour you have ever seen is a position on this strip, or a mixture of positions

Properties of Light

  • Visible range: 390-700nm

  • Luminance has a huge dynamic range (cd/m²):

    • 0.00003 — Moonless overcast night sky
    • 30 — Sky on overcast day
    • 3,000 — Sky on clear day
    • 16,000 — Snowy ground in full sunlight
  • Colors result from spectral curves:

    • Dominant wavelength → Hue
    • Brightness → Lightness
    • Purity → Saturation

Physiology of the Eye

Light is focused through cornea, pupil and lens onto the retina, where photons become signals

The Retina Structure

  • Wired upside down: light passes the nerve fibres, ganglion and bipolar cells before reaching the photoreceptors
  • Signals run back the other way: photoreceptor, bipolar, ganglion, optic nerve
  • ~100 million receptors converge on ~1 million ganglion axons: contrast and opponent differences are computed here, before anything leaves the eye
  • In the fovea the overlying layers are pushed aside so light hits the cones directly

Photoreceptors: Rods and Cones

Rods

  • Active at low light levels (scotopic vision)
  • Only one wavelength-sensitivity function
  • ~120 million in human eye

Cones

  • Active at normal light levels (photopic vision)
  • Three types with different peak sensitivities
  • ~6 million in human eye
  • Concentrated in fovea

Cone Sensitivity Curves

  • Three cone types: S (short, peak ~445 nm), M (medium, ~545 nm), L (long, ~565 nm)
  • The curves overlap, so no wavelength excites one cone type alone
  • M and L are only ~20 nm apart, which is why red-green deficiency is the common one
  • S cones are sparse and far from the others: blue carries the least detail

Density of Cones Across Retina

  • Cones (dashed) are packed into the fovea, the central ~2°, at up to ~150,000 per mm²
  • Rods (solid) peak about 20° out and are absent from the fovea
  • The gap at the optic disk is the blind spot
  • You have colour vision only where you are looking: peripheral colour coding does not work

Rods vs. Cones Sensitivity

Rods (scotopic) peak near 507 nm and see no colour; cones (photopic) peak near 555 nm and carry it

How We Perceive Color

A spectrum is reduced to three cone responses; spectra with the same three numbers look identical (metamers)

Opponent Process Theory

Three Opponent Channels

Color Opposition:

  • 🔴 Red ↔︎️ Green 🟢 (cannot see “reddish-green”)
  • 🔵 Blue ↔︎️ Yellow 🟡 (cannot see “yellowish-blue”)
  • ⚫ Black ↔︎️ White ⚪ (luminance channel)

Key Insights:

  • Explains why we see afterimages in complementary colors
  • Processed in retinal ganglion cells and LGN
  • Some cells excited by red, inhibited by green (and vice versa)
  • Explains unique hues: red, green, blue, yellow

Opponent Process Applications

Practical Impact:

  • Color space design: LAB uses opponent channels (A = red-green, B = blue-yellow)
  • Categorical perception: Explains why we naturally group colors into categories
  • Accessible color choices: Understanding oppositions guides colorblind-safe palettes

Demonstrations you can run in class:

  1. Afterimage - stare at a red square for 30 s, look at white, see green
  2. Impossible colours - try to picture a reddish green or a yellowish blue

Color Matching Experiments

Any colour can be matched by adjusting three primaries: the empirical basis of trichromacy

Color Models for Visualization

Trichromacy

Humans perceive colors through three channels

Most useful color description for visualization:

  • Hue: What color (red, blue, green…)
  • Saturation: Purity of color
  • Luminance/Lightness: Brightness

Just Noticeable Difference (JND)

The smallest detectable difference in a stimulus

For Color:

  • Luminance: ~1-2% change detectable
  • Hue: Varies by wavelength (most sensitive in blue-green)
  • Saturation: ~5-10% change needed

Implications for Visualization:

  • Need sufficient steps between colors in a scale
  • Can’t encode too many distinct values
  • Background affects perception (simultaneous contrast)

How Do We Use Color in Visualization?

Two primary purposes:

1. Quantify

Show numerical values

2. Label

Distinguish categories

Color to Quantify

Quantify: luminance carries the number, light means low and dark means high

Color to Label

  • Label: distinct hues at similar lightness, no implied order
  • Land cover around Portland: water, ice, urban, forest, scrub, grass, crops, wetlands
  • Semantically resonant choices (blue water, green forest) make the legend almost unnecessary
  • Keep saturation consistent, or one category will dominate

Quantitative Color Scales

Desired Properties:

  • Uniformity: Value difference = Perceived difference
  • Discriminability: As many distinct values as possible

Challenge:

Human perception is non-linear!

Single Hue Sequential Scales

**The luminance (L*) channel falls monotonically from light to dark; that ordering, not the blueness, encodes the value**

Categorical Color Scales

  • U.S. county unemployment, a quantity, drawn with a categorical palette: nothing reads as high or low
  • Categorical palettes want uniform saliency: nothing stands out unintentionally
  • And maximum discriminability: each category clearly distinct
  • The right tool for labels, the wrong tool for a quantity

Categorical Scale Limits

How many distinct colors can we use effectively?

Research suggests: 5-10 distinct categories maximum

Beyond this limit:

  • Colors become confusable
  • Need additional encoding (shape, pattern)
  • Consider grouping categories

Diverging Color Scales

For data with meaningful midpoint (zero, average, neutral)

Sequential scale obscures the critical 50% threshold

Diverging scale clearly shows above/below threshold

Color Context Effects

Simultaneous Contrast

The same color appears different depending on surrounding colors

Key Effects:

  • Colors appear lighter on dark backgrounds
  • Colors appear more saturated next to gray
  • Complementary colors enhance each other

Design Implications:

  • Test colors in context, not isolation
  • Be consistent with backgrounds
  • Use borders/whitespace to separate regions
  • Consider the whole visualization, not just the palette

Semantic Color Associations

Cultural and Contextual Meanings

Universal Associations:

  • Red: Heat, danger, stop 🔥 🛑
  • Blue: Cold, water, calm 💧 ❄️
  • Green: Nature, growth, go 🌱 ✅
  • Yellow: Caution, energy ⚠️ ⚡

Domain-Specific:

  • Finance: Red = loss (↓), Green = profit (↑)
  • Politics: Red/Blue = parties (varies by country!)
  • Temperature: Blue = cold ❄️, Red = hot 🌡️
  • Health: Red = critical 🚨, Yellow = warning ⚠️, Green = normal ✅

Color Blindness Considerations

About 8% of men and 0.5% of women have a colour vision deficiency, mostly red-green

Color Vision Simulators

Tools for Testing Accessibility

Browser Extensions:

Design Software Plugins:

  • Adobe Photoshop: View → Proof Setup → Color Blindness
  • Sketch: Stark plugin for accessibility testing
  • Figma: Able plugin for color vision simulation

Online Simulators:

Original, then deuteranope, protanope and tritanope simulations

Best Practice: Always test your visualizations with simulators during development, not after

Color Spaces

RGB (Red, Green, Blue)

  • Device-oriented
  • Not perceptually uniform
  • Common in programming

HSL/HSV (Hue, Saturation, Lightness/Value)

  • More intuitive for humans
  • Better for color selection
  • Still not perceptually uniform

LAB/LCH

  • Perceptually uniform
  • Better for interpolation
  • Used in professional design

Perceptual Color Spaces

Why Perceptual Uniformity Matters

In RGB space, equal numerical steps ≠ equal perceptual steps

// RGB interpolation can produce muddy colors
d3.interpolateRgb("red", "blue")

// LAB interpolation maintains perceptual uniformity
d3.interpolateLab("red", "blue")

// HCL even better for many visualizations
d3.interpolateHcl("red", "blue")

Design Implications of Color Processing

From Biology to Design

Our visual system’s structure creates constraints and opportunities:

Three Opponent Channels Process Color:

  • Luminance (Black-White): Best for detail and patterns
  • Red-Green: Categorical distinctions
  • Yellow-Blue: Categorical distinctions (weaker than red-green)

Key Biological Facts:

  • Far fewer blue-sensitive cones (~2% of total)
  • Blue cones less sensitive than red/green
  • Chromatic channels cannot convey fine detail

Luminance Contrast is Critical for Detail

Text and Fine Details Require Strong Luminance Contrast

ISO Standard Recommendation:

  • Minimum 3:1 luminance ratio between text and background
  • Chromatic channels (red-green, yellow-blue) cannot convey fine detail

Common Mistakes:

  • ❌ Blue text on dark backgrounds (illegible - lacks luminance contrast)
  • ❌ Red text on green background (relies only on chromatic contrast)
  • ✅ Black text on white (maximum luminance contrast)
  • ✅ High-contrast text with color used sparingly for emphasis

Color Coding Limitations

How Many Colors Can Users Distinguish?

Research Finding: Only 6-12 colors work reliably as codes

Best Practice - Use Unique Hues First:

  1. 🔴 Red
  2. 🟢 Green
  3. 🟡 Yellow
  4. 🔵 Blue
  5. Black
  6. White

Why These Work Best:

  • Most easily learned and identified
  • Correspond to opponent channel structure
  • Universal across cultures (mostly)

Beyond 6 categories? Add redundant encoding (shape, pattern, labels)

Size-Dependent Color Choices

Small Symbols vs. Large Areas

Small Symbols/Text

Requirements:

  • Strong, saturated colors
  • High luminance contrast with background
  • Avoid subtle color differences

Examples:

  • Points on scatter plots
  • Line graphs
  • Small icons
  • Text labels

Large Areas

Requirements:

  • Subdued, low-saturation colors
  • Avoid overwhelming the design
  • Prevent contrast effects on smaller elements

Examples:

  • Background fills
  • Map regions
  • Area charts
  • Dashboard panels

Simultaneous Contrast & Design Practice

Context Affects Color Perception

Simultaneous Contrast Effects:

  • Backgrounds affect small color patches more than vice versa
  • Same color appears different on different backgrounds
  • Critical for visualization design

Highlighting Best Practices:

  • Maintain or increase luminance contrast for emphasis
  • ❌ Common mistake: Reducing contrast (e.g., light text on light highlight)
  • ✅ Dark text on light highlight, or light text on dark highlight

Shape and Color Together:

  • Light-colored patterns interfere less with shape perception
  • Dark saturated patterns dominate and obscure 3D shape

D3 Color Scales

Sequential Scales

// Single hue
const blueScale = d3.scaleSequential()
  .domain([0, 100])
  .interpolator(d3.interpolateBlues);

// Multi-hue
const viridisScale = d3.scaleSequential()
  .domain([0, 100])
  .interpolator(d3.interpolateViridis);

Built-in Color Schemes:

  • Blues, Greens, Reds, Purples, Oranges, Greys
  • Viridis, Inferno, Magma, Plasma (perceptually uniform)

D3 Diverging Scales

// Diverging scale with custom midpoint
const divergingScale = d3.scaleDiverging()
  .domain([-50, 0, 100])  // min, midpoint, max
  .interpolator(d3.interpolateRdBu);

// Common diverging schemes:
// RdBu (red-blue), RdYlGn (red-yellow-green),
// BrBG (brown-green), PuOr (purple-orange)

Perfect for:

  • Temperature anomalies
  • Election results
  • Profit/loss
  • Any data with meaningful zero

D3 Categorical Scales

// Ordinal scale with color scheme
const categoryScale = d3.scaleOrdinal()
  .domain(["A", "B", "C", "D"])
  .range(d3.schemeCategory10);

// Available categorical schemes:
// schemeCategory10 - 10 distinct colors
// schemeSet1 - 9 saturated colors (NOT colorblind-safe)
// schemeSet2 - 8 muted colors (print friendly)
// schemeDark2 - 8 colors, the safest Brewer set for CVD
// schemeTableau10 - 10 colors, Tableau default
// schemeSet3 - 12 colors (pastel)
// schemePaired - 12 colors (paired)

Color Scale Best Practices

Sequential Data

✅ Use single or multi-hue sequential

❌ Don’t use rainbow scales

Categorical Data

✅ Use distinct hues with similar saturation/lightness

❌ Don’t use more than ~8 categories

Diverging Data

✅ Use when there’s a meaningful midpoint

❌ Don’t use for purely positive data

Accessibility

✅ Test with colorblind simulators

✅ Provide redundant encoding when possible

D3 Data Transformation Scales (Beyond Color)

Time Scales

const timeScale = d3.scaleTime()
  .domain([new Date(2020, 0, 1), new Date(2025, 0, 1)])
  .range([0, width]);

Log Scales

const logScale = d3.scaleLog()
  .domain([1, 1000])
  .range([0, width]);

Power Scales

const sqrtScale = d3.scaleSqrt()  // same as scalePow().exponent(0.5)
  .domain([0, 100])
  .range([0, width]);

Quantized Scales

Transform continuous domains into discrete ranges

// Quantize scale - equal intervals
const quantizeScale = d3.scaleQuantize()
  .domain([0, 100])
  .range(["low", "medium", "high"]);

// Quantile scale - equal quantities
const quantileScale = d3.scaleQuantile()
  .domain(data)
  .range(["Q1", "Q2", "Q3", "Q4"]);

// Threshold scale - custom breakpoints
const thresholdScale = d3.scaleThreshold()
  .domain([30, 70])
  .range(["cold", "comfortable", "hot"]);

Color Interpolation

D3 provides multiple interpolation methods:

// RGB interpolation (can be muddy)
d3.interpolateRgb("red", "blue")(0.5);

// HSL interpolation (follows hue wheel)
d3.interpolateHsl("red", "blue")(0.5);

// LAB interpolation (perceptually uniform)
d3.interpolateLab("red", "blue")(0.5);

// HCL interpolation (best for many cases)
d3.interpolateHcl("red", "blue")(0.5);

// Cubehelix (multi-hue with monotonic luminance)
d3.interpolateCubehelix("red", "blue")(0.5);

Creating Custom Color Scales

// Custom sequential scale
const customSequential = d3.scaleSequential()
  .domain([0, 100])
  .interpolator(t => d3.interpolateHcl("#e8f4f8", "#004c6d")(t));

// Custom diverging scale
const customDiverging = d3.scaleDiverging()
  .domain([-1, 0, 1])
  .interpolator(t => t < 0.5
    ? d3.interpolateHcl("#67001f", "#f7f7f7")(t * 2)
    : d3.interpolateHcl("#f7f7f7", "#053061")((t - 0.5) * 2));

// Piecewise scale
const piecewise = d3.scaleLinear()
  .domain([0, 50, 100])
  .range(["#2166ac", "#f7f7f7", "#b2182b"]);

Practical Color Guidelines

For Print

  • Consider grayscale reproduction
  • Use ColorBrewer schemes
  • Test on actual printer

For Screen

  • Consider monitor variations
  • Use sufficient contrast
  • Test on different devices

For Accessibility

  • Use colorblind-safe palettes
  • Provide alternative encodings
  • Test with simulators

Color Tools and Resources

Online Tools:

D3 Resources:

Research:

Common Color Mistakes

1. Don’t Use Rainbow Scales

Why: Perceptually non-uniform, creates false boundaries Instead: Use Viridis or single-hue sequential

2. Don’t Exceed 7-8 Categories

Why: Colors become indistinguishable Instead: Group data or use interactive filtering

3. Don’t Ignore Cultural Context

Why: Red = profit in Asia, loss in West Instead: Know your audience, test assumptions

4. Don’t Use Poor Contrast

Why: Fails WCAG accessibility standards Instead: Test contrast ratios (4.5:1 minimum)

Lab Preview: Color and Scales in D3

Today’s Lab Activities:

  1. Implement different scale types (linear, log, time)
  2. Create color scales for different data types
  3. Build a choropleth map with sequential colors
  4. Design accessible categorical palettes
  5. Test colorblind safety

Key Concepts to Practice:

  • Scale domains and ranges
  • Color interpolation methods
  • Legends for color scales
  • Interactive scale adjustments

Putting It All Together

Example: Temperature Visualization

// Temperature data with anomalies
const tempScale = d3.scaleDiverging()
  .domain([-10, 0, 10])  // Anomaly in degrees
  .interpolator(d3.interpolateRdBu)
  .clamp(true);  // Prevent extrapolation

// Apply to data
svg.selectAll("rect")
  .data(temperatureData)
  .enter().append("rect")
  .attr("fill", d => tempScale(d.anomaly))
  .attr("opacity", 0.8);  // Slight transparency

// Add legend (d3-svg-legend plugin, not core d3)
const legend = d3.legendColor()
  .scale(tempScale)
  .title("Temperature Anomaly (°C)");

Color Gamut and Display Limitations

Not All Colors Are Equal

Display Constraints:

  • sRGB: Standard web/monitor gamut (most limited)
  • Adobe RGB: Wider gamut for professional displays
  • P3: Modern displays (iPhone, Mac)
  • Print CMYK: Different gamut than screens

Practical Implications:

  • Highly saturated colors may not reproduce
  • Test on target devices
  • Provide fallbacks for older displays
  • Consider print requirements early

Summary: Key Concepts

Vision & Perception

  • Trichromatic vision: 3 cone types → 3D color space
  • Non-uniform perception: JND varies by channel
  • Foveal concentration: Color discrimination best in center

Color Uses in Visualization

  • Sequential: Ordered data (light → dark)
  • Diverging: Data with meaningful midpoint
  • Categorical: Distinct groups (max 5-8)

Accessibility is Essential

  • ~8% of men, 0.5% of women have a colour vision deficiency (mostly red-green)
  • Always provide redundant encoding
  • Test with simulators before deployment

Summary: Implementation & Practices

D3 Color Implementation

  • Perceptual spaces: Use LAB/HCL for interpolation
  • Built-in schemes: Viridis, ColorBrewer, etc.
  • Scale types: Sequential, diverging, ordinal

Critical Best Practices

  • Avoid rainbow scales for continuous data
  • Maintain uniform saliency in categories
  • Consider display gamut (sRGB for web)

Testing Checklist

✓ Colorblind safe? ✓ Prints in grayscale? ✓ Works on different displays? ✓ Context effects considered?

Next Week (Oct 9): Group Projects and Design Ethics

Topics:

  • Group project overview, timeline and the five milestones
  • Team formation and choosing a topic (NYC urban data)
  • Example projects and evaluation criteria
  • Deceptive visualization and design ethics

Due:

  • Exercise 5 - Color design with D3 scales (Oct 8)
  • Form teams by Oct 16

Required reading:

  • Tufte, The Visual Display of Quantitative Information, Chapter 2: Graphical Integrity
  • Misinformed by Visualization - Lo, Gupta & Shigyo, EuroVis 2022

Optional:

Required Readings

Core Papers & Resources

Which Color Scale to Use Lisa Charlotte Rost, Datawrapper Blog

  • Practical guide to choosing color scales
  • Covers sequential, diverging, and categorical palettes
  • Real-world examples from data journalism
  • Interactive examples you can modify

Modeling Color Difference Szafir, D.A. (2018). IEEE TVCG

  • Empirical study of color perception in visualization
  • Shows RGB interpolation problems
  • Proposes perceptually-uniform color models
  • Critical for understanding why we use LAB/HCL

D3 Scale Chromatic Observable Interactive Notebook

  • Live code examples of all D3 color schemes
  • Interactive comparisons between scales
  • Copy-paste ready code snippets
  • Includes accessibility information

Optional Readings

Advanced Color Theory

Somewhere Over the Rainbow Liu, Y. & Heer, J. (2018). CHI 2018

  • Large-scale empirical study (n=9,871 participants)
  • Quantifies effectiveness of different color scales
  • Proves why rainbow colormaps are problematic
  • Recommendations: single-hue and multi-hue scales outperform rainbow

Color Use Guidelines for Mapping Brewer, C.A. (1994). Cartography and GIS

  • Foundation of ColorBrewer tool
  • Systematic approach to color selection
  • Addresses print, screen, and colorblind considerations
  • Still the definitive reference 30 years later

The Viridis Color Palettes Garnier et al. (2021)

  • Story behind the most popular scientific colormap
  • Perceptually uniform, colorblind-safe, print-friendly
  • Mathematical derivation and testing methodology

Color Naming Models for Color Selection Heer, J. & Stone, M. (2012). IEEE CG&A

  • Data-driven approach to color selection using natural language
  • Based on XKCD color survey with 3.5 million judgments
  • Probabilistic model for color naming and selection
  • Foundation for many modern color tools

Visual Thinking for Information Design (2nd Edition) Colin Ware (Morgan Kaufmann, 2022)

  • Comprehensive coverage of color perception
  • Practical design guidelines
  • Chapters on color theory and visual encoding