Skip to Content
Open to AI related Platform Engineer, DevOps, SRE Roles in Seattle(US), SF(US), or Vancouver(BC) • Available for onsite/hybrid.
BlogD3 for Data and Visual Analytics

D3.js  (Data-Driven Documents) is a JavaScript library for producing dynamic, interactive data visualizations in the browser. Rather than shipping fixed chart types, D3 gives you low-level building blocks: you bind data to the DOM/SVG and control exactly how it is drawn. I first worked with it in the Georgia Tech OMSCS course CSE 6242: Data and Visual Analytics .

Core concepts

  • Selections — D3 selects DOM elements (d3.select, d3.selectAll) and applies operations to the whole selection at once.
  • Data bindingselection.data(values) joins an array to elements. The enter set creates elements for new data, update changes existing ones, and exit removes stale ones. This join is the heart of D3.
  • Scales — functions that map a data domain to a pixel/color range, such as d3.scaleLinear, d3.scaleBand, and d3.scaleOrdinal.
  • Axes and shapes — generators (d3.axisBottom, d3.line, d3.arc) emit the SVG for common chart furniture.

A minimal bar chart

This draws a bar chart into an existing <svg>, using a band scale for the categories and a linear scale for the values:

const data = [4, 8, 15, 16, 23, 42]; const width = 400; const height = 200; const x = d3.scaleBand() .domain(data.map((_, i) => i)) .range([0, width]) .padding(0.1); const y = d3.scaleLinear() .domain([0, d3.max(data)]) .range([height, 0]); const svg = d3.select("svg").attr("width", width).attr("height", height); svg.selectAll("rect") .data(data) .join("rect") // enter + update + exit in one call (D3 v5+) .attr("x", (_, i) => x(i)) .attr("y", (d) => y(d)) .attr("width", x.bandwidth()) .attr("height", (d) => height - y(d)) .attr("fill", "#2c5364");

SVG vs. Canvas

D3 usually renders to SVG, which is easy to style and inspect and keeps every mark in the DOM. For very large datasets (tens of thousands of marks), render to Canvas instead to avoid DOM overhead, and use D3 only for the scales and layout math.

Testing D3 code

Keep the data-to-attribute math in small pure functions (like the scale setup above) so it can be unit-tested without a browser. For component-level rendering tests, see Unit Testing React and D3 with Jest .

Further reading

Last updated on