Fork me on GitHub

D3's Data Binding, An Interactive Explanation

by Krist Wongsuphasawat (@kristw) / Feb 20, 2015

Visualization encodes data points into visual elements. D3.js embraces this concept by helping you bind each data point to a DOM element easily. Once you get these pairs figured out, it is very straightforward to set the styles or attributes of the elements to according to the data points.

See the simulation

Press Step 1 and Step 2, then repeat. You should see the chart below updated to show the data points in myData as bars. In the visualization below, the left side is an example chart that will be updated with new data dynamically. The diagram on the right side shows what actually happens in the background for this chart.

Next, see what happened when you pressed Step 1 (Bind data) one or more times without Step 2 (Update visual appearance)? Is the chart updated?

Bind data only updates the bindings in the background, but does not update the chart until Update visual appearance is called. To understand why, let's see the actual code and explanation below.

Explanation

Step 0. Select a container

var container = d3.select('svg');

Step 1. Bind data

The command below will bind each data point d in myData to <rect> (a rectangle) inside container using d.k as key.

var selection = container.selectAll('rect')
  .data(myData, function(d){ return d.k; });

After this step, you get a hold of selection, which gives you access to pairs between data point and DOM. There are three types of pairs in the selection:

  • enter: These are pairs with new data points that do not have corresponding DOMs yet. D3 will make you feel like you have placeholders for these DOMs that do not exist yet. They can be accessed via selection.enter()

Note: If you bind the data for the first time, every pair will be an enter pair. However, if you bind data for more than one time, you will see two more types of pairs.

  • update: The new data points which keys already exist are paired with existing DOMs with the same keys. They can be accessed via selection
  • exit: The data in these pairs do not exist anymore. They can be accessed via selection.exit()

Step 2. Update visual appearance

Creating a binding does not change anything on the screen until you do something with it. Here are the common actions you should take.

  • enter: Add the DOM. Remember that the enter pairs do not have DOMs yet.
    selection.enter().append('rect')
      .attr('y', function(d){return d.k * 10;})
      .attr('height', 9)
      .attr('width', function(d){return scale(d.v);});
  • update: The new data point may be different from the old one. They just have the same key. You should update the visual appearance to make sure.
    selection
      .attr('width', function(d){return scale(d.v);});
  • exit: The data are not there any more. Why should we still keep them? Remove!
    selection.exit().remove();