Shapes, paths, and colour
Shapes, Paths, and Colour
Section titled “Shapes, Paths, and Colour”The SVG backend bundles three libraries that raise the level of abstraction above hand-written SVG strings: d3-path for programmatic paths, d3-shape for data-driven shape generators, and chroma-js for colour manipulation.
d3-path — building path data
Section titled “d3-path — building path data”d3-path wraps the SVG path command set in a fluent API, so you call methods
instead of concatenating strings. When there is no canvas context attached it
serialises to an SVG path string automatically.
const { path } = require('d3-path')
const p = path()p.moveTo(50, 200)p.bezierCurveTo(100, 50, 300, 50, 350, 200)p.lineTo(300, 350)p.arc(200, 200, 50, Math.PI * 0.5, Math.PI * 1.5)p.closePath()
// p.toString() returns the SVG path data stringconst d = p.toString()// → "M50,200C100,50,300,50,350,200L300,350A50,50,0,1,1,..."Use the resulting string directly in a <path d="..."> element:
return `<svg ...> <path d="${p.toString()}" fill="none" stroke="#e94560" stroke-width="2" /></svg>`Available methods mirror the SVG path commands: moveTo, lineTo,
quadraticCurveTo, bezierCurveTo, arcTo, arc, rect, closePath.
pathRound(digits) works the same way but rounds coordinates to a fixed
number of decimal places.
d3-shape — generators for common shapes
Section titled “d3-shape — generators for common shapes”d3-shape builds on d3-path to provide higher-level generators that turn
data into path strings.
Line generator
Section titled “Line generator”Maps an array of data points to a smooth (or stepped, or straight) path:
const { line, curveCatmullRom } = require('d3-shape')
const data = [ { t: 0, v: 60 }, { t: 100, v: 20 }, { t: 200, v: 80 }, { t: 300, v: 40 }, { t: 400, v: 70 },]
const lineGen = line() .x(d => d.t) .y(d => d.v) .curve(curveCatmullRom) // smooth interpolation
const pathData = lineGen(data) // returns an SVG path stringSwap the .curve() for curveBasis, curveStep, curveMonotoneX, etc. —
each produces a different interpolation style.
Arc and pie generators
Section titled “Arc and pie generators”Use pie() to convert raw values into arc angle data, then arc() to turn
those arcs into path strings.
const { pie, arc } = require('d3-shape')
const values = [40, 30, 20, 10]
// pie() computes startAngle / endAngle for each valueconst slices = pie()(values)
// arc() turns angle data into an SVG path stringconst arcPath = arc() .innerRadius(60) // > 0 for donut, 0 for filled pie .outerRadius(140)
// Arcs are centred on (0,0) — use an SVG transform to repositionconst paths = slices.map(s => `<path d="${arcPath(s)}" />`)return `<svg ...> <g transform="translate(200, 200)"> ${paths.join('\n ')} </g></svg>`Other generators
Section titled “Other generators”| Generator | What it produces |
|---|---|
area() |
A filled area between two lines |
symbol() |
Small symbols: circle, cross, diamond, star, … |
linkHorizontal() / linkVertical() |
Smooth S-curve connectors |
stack() |
Stacked data for stacked bar / area charts |
chroma-js — colour manipulation
Section titled “chroma-js — colour manipulation”chroma-js is a default export — import the whole thing as a single function:
const chroma = require('chroma-js')Creating colours
Section titled “Creating colours”chroma('#e94560') // from hexchroma(233, 69, 96) // from RGB values 0–255chroma(349, 0.8, 0.59, 'hsl') // from HSLchroma('tomato') // from CSS nameManipulating a colour
Section titled “Manipulating a colour”const c = chroma('#e94560')c.hex() // '#e94560'c.rgb() // [233, 69, 96]c.brighten(1).hex() // lighter versionc.darken(0.5).hex() // darker versionc.saturate(2).hex() // more saturatedc.alpha(0.5).css() // 'rgba(233,69,96,0.5)'Colour scales
Section titled “Colour scales”The most useful feature for visualisation: map a [0, 1] value to a colour
along a gradient.
// Two-colour scaleconst scale = chroma.scale(['#0f3460', '#e94560']).mode('lab')scale(0).hex() // '#0f3460'scale(0.5).hex() // midpointscale(1).hex() // '#e94560'
// Multi-colour scale with domain stopsconst terrain = chroma.scale(['#1a6091', '#87a96b', '#7a6044', '#ffffff']) .domain([0, 0.4, 0.75, 1.0]) .mode('lab')
// Generate N evenly-spaced colours from a scaleconst palette = chroma.scale(['#e94560', '#0f3460']).colors(8)// → ['#e94560', '#c63567', ...8 hex strings...]
// Mix two colourschroma.mix('#e94560', '#0f3460', 0.5, 'lab').hex()The .mode('lab') call uses the perceptually-uniform CIELAB colour space,
which usually produces more natural-looking transitions than the default
'rgb' mode.
Worked example: pie chart
Section titled “Worked example: pie chart”Combining all three libraries into a self-contained chart:
const { pie, arc } = require('d3-shape')const chroma = require('chroma-js')
function main({ size }) { const cx = size / 2, cy = size / 2 const outerR = size * 0.38, innerR = size * 0.18
const data = [{ label: 'A', v: 38 }, { label: 'B', v: 28 }, { label: 'C', v: 20 }, { label: 'D', v: 14 }] const slices = pie().value(d => d.v).padAngle(0.025)(data) const arcGen = arc().innerRadius(innerR).outerRadius(outerR) const colors = chroma.scale(['#e94560', '#533483', '#0f3460', '#0a9396']).colors(data.length)
const paths = slices.map((s, i) => `<path d="${arcGen(s)}" fill="${colors[i]}" />` )
return `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 ${size} ${size}"> <rect width="${size}" height="${size}" fill="#0d1b2e"/> <g transform="translate(${cx},${cy})">${paths.join('')}</g> </svg>`}
module.exports = { main }Next steps
Section titled “Next steps”- Browse the Edit imports… overlay to see every exported function from d3-shape grouped by category.
- Look at the Donut chart and Lissajous grid examples for more complete demonstrations.