Color Theory and D3 Scales

CS-GY 6313 - Fall 2025

Claudio Silva

NYU Tandon School of Engineering

2025-10-03

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 approximately 390-700nm

Properties of Light

  • Visible range: 390-700nm

  • Luminance has huge dynamic range:

    • 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 passes through cornea, pupil, lens, and reaches the retina

The Retina Structure

Multiple layers of cells process visual information before sending to brain

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 types of cones: S (short/blue), M (medium/green), L (long/red)

Density of Cones Across Retina

Highest density in fovea (center of vision)

Rods vs. Cones Sensitivity

Rods more sensitive in low light; cones provide color vision

How We Perceive Color

Color perception results from brain’s interpretation of cone responses

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

Visual Demonstrations:

  1. Afterimage demonstration - Stare at red dot → see green afterimage
  2. Opponent channel diagram - Neural wiring showing R+/G- and B+/Y- cells
  3. Color wheel showing oppositions - Traditional wheel with opponent pairs
  4. Impossible colors - Why we can’t see reddish-green

Color Matching Experiments

Foundation of color theory: any color can be matched with three primaries

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

Mapping numerical values to color intensity or hue

Color to Label

Using distinct colors to represent different categories

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

Best for quantitative data with natural ordering

Key Insight: The luminance (L*) channel decreases monotonically from light to dark, creating the perception of ordered values

Categorical Color Scales

For nominal/categorical data without inherent order

Design Goals:

  • Uniform saliency: Nothing stands out unintentionally
  • Maximum discriminability: Each category clearly distinct

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

The two center gray squares are EXACTLY the same color (RGB 128, 128, 128) - a classic demonstration often attributed to Josef Albers
  • 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

~10% of males and ~1% of females have color vision deficiencies

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:

Different types of color vision deficiencies: Deuteranope (red-green), Protanope (red-green), Tritanope (blue-yellow)

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 colors (colorblind safe)
// schemeSet2 - 8 colors (print friendly)
// 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 (rainbow with uniform 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
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

  • ~10% color 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: Deceptive Visualizations

Topics:

  • Types of visual deception
  • Intentional vs. unintentional misleading
  • Cognitive biases in interpretation
  • Ethical responsibilities
  • Case studies from media

Pre-reading:

  • Tufte Chapter 2: “Graphical Integrity”
  • “Truncating the Y-Axis: Threat or Menace?”

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