Declarative chart spec vs D3
One line chart built twice, as a 45-line JSON spec and in 97 lines of D3, to show what each approach costs and gives you.
Made with OpenChart. How to build this line chart
More developers pushed TypeScript code to GitHub than Java code for the first time in the third quarter of 2023, and the TypeScript count has grown 9.1 times since early 2020. Here is that chart built both ways. A declarative spec describes the chart and lets a library draw it; D3 gives you scales, shapes and axes, and you assemble the chart from them.
Made with OpenChart. How to build this line chart
The spec is 45 lines, not counting the 50 data rows. It says which fields go on which axes, which colors to use, and what the title is. It does not say where anything goes on the page.
The same chart in D3
The D3 version runs on the same rows and draws the same lines, axes, end labels and callout. It takes 97 lines of TypeScript. Two jobs the spec never mentions take a good share of them: breaking the title into lines, because SVG text does not wrap, and placing the callout by hand.
import * as d3 from "d3";
type Row = { date: Date; language: string; pushers: number };
export function drawChart(
container: HTMLElement,
data: { date: string; language: string; pushers: number }[],
title: string,
subtitle: string,
) {
const width = 720;
const height = 420;
const margin = { top: 104, right: 140, bottom: 36, left: 56 };
const colors: Record<string, string> = { TypeScript: "#0e7490", Java: "#66707a" };
const rows: Row[] = data.map((d) => ({ ...d, date: d3.timeParse("%Y-%m-%d")(d.date) as Date }));
const series = d3.group(rows, (d) => d.language);
const x = d3
.scaleTime()
.domain(d3.extent(rows, (d) => d.date) as [Date, Date])
.range([margin.left, width - margin.right]);
const y = d3
.scaleLinear()
.domain([0, d3.max(rows, (d) => d.pushers) as number])
.nice()
.range([height - margin.bottom, margin.top]);
const svg = d3
.select(container)
.append("svg")
.attr("viewBox", `0 0 ${width} ${height}`)
.attr("role", "img")
.attr("aria-label", title);
// SVG text does not wrap, so break the title into lines (two fit above the subtitle).
const heading = svg.append("text").attr("font-size", 22);
let words: string[] = [];
let tspan = heading.append("tspan").attr("x", margin.left).attr("y", 30);
for (const word of title.split(" ")) {
tspan.text([...words, word].join(" "));
if (words.length > 0 && tspan.node()!.getComputedTextLength() > width - margin.left - margin.right) {
tspan.text(words.join(" "));
words = [];
tspan = heading.append("tspan").attr("x", margin.left).attr("dy", 26);
}
words.push(word);
tspan.text(words.join(" "));
}
svg.append("text").attr("x", margin.left).attr("y", 78).attr("fill", "#555").text(subtitle);
svg
.append("g")
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(d3.axisBottom(x).ticks(6).tickFormat(d3.timeFormat("%Y") as never));
svg
.append("g")
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(y).ticks(5, "~s").tickSize(-(width - margin.left - margin.right)))
.call((g) => g.select(".domain").remove())
.call((g) => g.selectAll(".tick line").attr("stroke", "#ddd"));
const line = d3
.line<Row>()
.x((d) => x(d.date))
.y((d) => y(d.pushers));
for (const [language, points] of series) {
svg
.append("path")
.datum(points)
.attr("fill", "none")
.attr("stroke", colors[language])
.attr("stroke-width", 2.5)
.attr("d", line);
const last = points[points.length - 1];
svg
.append("text")
.attr("x", x(last.date) + 8)
.attr("y", y(last.pushers))
.attr("dy", "0.35em")
.attr("fill", colors[language])
.text(`${language} ${d3.format(".3~s")(last.pushers)}`);
}
// Mark the first quarter TypeScript is ahead. Both series list the same quarters in order.
const java = series.get("Java")!;
const cross = series.get("TypeScript")!.find((d, i) => d.pushers > java[i].pushers)!;
const [cx, cy] = [x(cross.date), y(cross.pushers)];
const quarter = `${cross.date.getFullYear()} Q${Math.floor(cross.date.getMonth() / 3) + 1}`;
svg.append("line").attr("stroke", "#888")
.attr("x1", cx).attr("y1", cy).attr("x2", cx - 90).attr("y2", cy - 60);
svg.append("circle").attr("fill", "#fff").attr("stroke", "#888")
.attr("cx", cx).attr("cy", cy).attr("r", 4);
svg.append("text").attr("text-anchor", "middle")
.attr("x", cx - 90).attr("y", cy - 66).text(`${quarter}: TypeScript passes Java`);
}Most of those lines are decisions the spec made for you: the margins, the pixel range of each scale, how the axes are built, where the labels go.
Responsive layout and accessibility
The spec version adapts to a phone, works with a keyboard and a screen reader, animates and exports, all without extra code. On a phone-width container the chart switches to a compact layout with fewer ticks, and the callout becomes a numbered note under the plot. Annotations sit in data coordinates, so a callout stays on its point when the chart resizes.
The chart can be tabbed to and stepped through with the arrow keys, with a tooltip at each step. It has a hidden data table and a label for screen readers, its entrance animates, and it exports to SVG and PNG.
The D3 chart scales as a picture, so its text shrinks with its width. It has the aria-label the code sets by hand and none of the rest. D3 can do all of it, and you write each piece.
Limits of a spec
A spec can only describe charts the library knows how to draw. You also take the library’s defaults for spacing, type and color, and you override them through spec fields where a field exists, which is a narrower set of choices than raw SVG.
Changing a spec is cheap inside that range. The chart below swaps mark for a range and adds a second position channel, x2, so each bar runs from the 10th to the 90th percentile of pay. A color field picks out the two groups the title compares, and a reference rule marks the managers’ $60,130. In D3 the move from lines to ranges touches the line generator, the labels and the scales.
Made with OpenChart. How to build this range chart
When to use D3
Use D3 when the chart is the product: a custom layout, a mark that no chart type draws, or an interaction the spec cannot describe. Use a spec when the chart is a standard one and the work is in the data and the writing.
The spec
data holds one row per quarter and language, with the quarter turned into a date so the x axis can be a time axis. In encoding, each channel names a field and a type. x is temporal, y is quantitative with scale.zero set so the axis starts at zero as the D3 version does, and color splits the rows into one line per language, its domain fixes the order, and theme.colors.categorical gives each line a light and a dark color.
endpointLabels names each line at its right end in place of a legend, and chrome holds the title and subtitle. The encoding page lists every channel.
The callout in annotations sits at a data position, an x date and a y count, so it stays on the crossing point at any width. offset moves the text away from the point and connector draws the line back to it. chromeLayout: "subtract" keeps the figure at its height when the callout turns into a note on a phone.
The anatomy of a spec takes one published chart apart a block at a time.