Code

D3.js

Data Binding

Beginner Bind an array of values to DOM elements using the .join() enter/update/exit pattern — the heart of every D3 visualisation. d3-selection/joining

const data = [42, 78, 55, 91, 34, 67, 83, 28, 60, 47];

// Data join using .join()
svg.selectAll('rect')
  .data(data)          // bind data
  .join('rect')        // enter + update + exit
  .attr('x',  (_, i) => i * colW)
  .attr('y',  d => height - scale(d))
  .attr('width',  colW - 4)
  .attr('height', d => scale(d))
  .attr('fill', (_, i) => color(i))
  .attr('rx', 4);

// Value labels bound to same data
svg.selectAll('text.val')
  .data(data)
  .join('text')
  .attr('x', (_, i) => i * colW + colW / 2)
  .attr('y', d => height - scale(d) - 4)
  .attr('text-anchor', 'middle')
  .text(d => d);
Key APIs
  • .data(array) — binds an array to a selection
  • .join(tag) — handles enter, update, and exit in one call
  • selection.enter() — elements that need to be created
  • selection.exit() — elements that should be removed
  • Accessor functions (d, i) => … receive the datum d and index i