Notes on D3

Published on November 8, 2015
Some notes on using d3.js simply for table management, without further visualisations.

Last year we picked up d3 to clean up a couple of horrendous pages of javascript doing basic dom manipulation. I thought at the time that I should do a lighning talk or workshop for those who hadn’t used d3 before, but never got around to it. Now I’m just recording the notes I would have used as a basis.

Docs here.

Introducing d3 concepts

To introduce a new field
  • select() single element
  • bind data
  • enter() [append(), text()]
To update a field
  • select() single element
  • bind data
  • update() [text()]
To remove a field
  • select() single element
  • bind data
  • exit() [remove()]

Normal usage pattern, e.g. for rows in a table

To handle multiple fields at once
  • selectAll() multiple elements
  • bind data with key function
  • enter() [append(), text()]
  • exit() [remove()]
  • update()
To handle hardcoded nested data per field
  • selectAll() multiple elements
  • bind data with key function
  • select() single sub element, for nested select
  • enter() [append(), text()]
  • exit() [remove()]
  • update()
To handle arbitrary nested data per field
  • selectAll() multiple elements
  • bind data with key function
  • selectAll() multiple sub elements, for nested select
  • enter() [append(), text()]
  • exit() [remove()]
  • update()

Virtual dom representation

Notice that d3 selections are always represented as array of arrays - this covers single element, multiple elements, single subselect, multiple subselect.

Notice differing availablility of bound data as a result, and that data bound at the top level in the array of array form will end up binding elements to leaves.

  • what happens when you selectAll().select().selectAll(), or when you selectAll().selectAll(), or when you select().select(), or when you select().selectAll()

Classes and attributes

  • select single element
  • bind data
  • enter() [append(), classed(), attr()]
  • notice what happens when you attr() twice in a row. This is an easy pitfall. Also show the interaction with classed().

Ordered data

sort(), ascending(), descending(), insert()

Data binding

  • data(), to set the value on a particular selection (before updating that selection)
  • datum(), to transform the value on a particular selection (before updating that selection)
  • Full explanation here

Events

  • attach handlers to a selection e.g. selectAll().on(“click” foo)

Effects

  • each() - perform an effect across the selection

Aside

An example of using d3 to create a timeline.