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.
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.
var container = d3.select('svg');
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:
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.
selection
selection.exit()
Creating a binding does not change anything on the screen until you do something with it. Here are the common actions you should take.
selection.enter().append('rect') .attr('y', function(d){return d.k * 10;}) .attr('height', 9) .attr('width', function(d){return scale(d.v);});
selection .attr('width', function(d){return scale(d.v);});
selection.exit().remove();