liveBook · Manning

Defs element

As explained in D3.js in Action, Third Edition

An SVG defs element contains graphical definitions that are not rendered directly but can be referenced by other SVG elements.

An SVG <defs> element stores graphical definitions for later reuse instead of rendering them directly. It can contain patterns, gradients, and blurs. section 10.2.2

In an accessible scatterplot, append <defs> to the SVG container, then append reusable <pattern> elements inside it. Each pattern needs a unique ID so another shape can reference it. section 10.2.2

Creating and applying a pattern

const defs = d3.select("#scatterplot svg").append("defs"); const horizontalLinesPattern = defs .append("pattern") .attr("id", "pattern-horizontal-lines") .attr("width", 4) .attr("height", 4) .attr("patternUnits", "userSpaceOnUse"); horizontalLinesPattern.append("rect") .attr("width", "100%").attr("height", "100%") .attr("fill", "#fff"); horizontalLinesPattern.append("line") .attr("x1", 0).attr("y1", 2) .attr("x2", 4).attr("y2", 2) .attr("stroke", colorScale("NT")); // Apply the definition to matching circles d3.selectAll(".cetacean-NT") .attr("fill", "url(#pattern-horizontal-lines)");

Pattern tiles repeat horizontally and vertically. Combining each pattern with a categorical color encodes conservation status in two ways, helping users who cannot reliably distinguish colors. section 10.2.2 section 10.3

How D3.js in Action, Third Edition covers it

How deep it goes
Explains creation, tiling, unique IDs, and URL-based application, but does not cover gradients or blur implementations.
Examples
Uses cetacean conservation-status circles filled with horizontal lines, dots, stars, vertical lines, or crosses.
What it assumes
Assumes basic SVG shapes and D3 selections while teaching definitions, pattern tiles, and reuse through a concrete visualization.
What you can do after
Build reusable SVG definitions and apply their patterns to D3-rendered shapes using unique URL references.
How it connects
Connects SVG patterns, D3 selections, scatterplots, accessibility, color blindness, and double encoding.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of D3.js in Action, Third Edition. The section links point to the parts of the book it draws on.