iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

JS D3.js

D3 (Data-Driven Documents) is the swiss army knife of web visualisation. Instead of giving you finished charts, it gives you primitives to bind data to DOM (usually SVG) and compute scales, axes, layouts, and projections.

The "Hello, D3" pattern

HTML
<svg id="chart" width="400" height="200"></svg>
<script src="https://cdn.jsdelivr.net/npm/d3@7"></script>
JS
const data = [12, 19, 17, 23, 7, 11];
const svg  = d3.select("#chart");

const x = d3.scaleBand().domain(d3.range(data.length)).range([0, 400]).padding(0.1);
const y = d3.scaleLinear().domain([0, d3.max(data)]).range([200, 0]);

svg.selectAll("rect")
   .data(data)
   .join("rect")
     .attr("x", (_, i) => x(i))
     .attr("y", d => y(d))
     .attr("width",  x.bandwidth())
     .attr("height", d => 200 - y(d))
     .attr("fill", "#04AA6D");

The mental model

  • Selection — choose DOM nodes (d3.select / selectAll).
  • Data join — bind data to nodes (.data(arr).join(tag)).
  • Scales — map data values to pixels.
  • Axes & layouts — generators for common chart pieces.
  • Transitions — interpolate attributes over time.

What D3 gives you beyond charts

ModuleUse for
d3-scaleLinear, log, time, ordinal mappings.
d3-geoMap projections from GeoJSON.
d3-forcePhysics-based network layouts.
d3-hierarchyTree, treemap, partition layouts.
d3-interpolateSmoothly tween any value.
Tip: Reach for Chart.js (or Observable Plot) when you need a finished chart. Reach for D3 when the chart is unusual enough that no library has it — D3 is a kit, not a chart factory.

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from JS D3.js!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Bind an array of values to rects.

svg.selectAll('rect'). (data).join('rect');

Test yourself

Q1. D3 stands for…
Q2. D3's primary output target is…
Q3. Bind data to DOM nodes with…

Discussion

Loading…