Recipe

D3 Basics

Bind data to DOM elements and create your first SVG chart with D3.js.

Setup

Include D3 via CDN or install with npm. This recipe uses a single HTML file with the CDN script tag for zero-config prototyping.

<script src="https://d3js.org/d3.v7.min.js"></script>

Selection & Data Binding

D3 selections are the core abstraction. Use d3.select to grab an element and .data() to bind an array. The enter-update-exit pattern handles dynamic data.

const svg = d3.select("#chart")
  .append("svg")
  .attr("width", 400)
  .attr("height", 200);

svg.selectAll("circle")
  .data([30, 80, 45, 60, 20])
  .enter()
  .append("circle")
  .attr("cx", (d, i) => i * 70 + 40)
  .attr("cy", 100)
  .attr("r", d => d)
  .attr("fill", "#8B5CF6");

Scales

Scales map data values to pixel coordinates. d3.scaleLinear() is the most common — it transforms a domain into a range.

const x = d3.scaleLinear()
  .domain([0, d3.max(data)])
  .range([0, 300]);

Axes

Generate axis lines and ticks with d3.axisBottom() or d3.axisLeft(). Call the result on a group element to render.

svg.append("g")
  .attr("transform", "translate(0,180)")
  .call(d3.axisBottom(x));
Meridian — data recipes for builders.