[Hold on] I've made a tool to help people building presentations the modern way.
If you are curious, here the starting point. [/Hold on]
join method of D3.js simplifies a lot introducing the library to newcomers.
One of the most difficult parts of D3.js to grasp has always been the brilliant
enter update exit strategy that manages the different phases required by any dynamic and interactive visualization built with the library.
The very recent 5.8.0 release introduces a new method to simplify that part, adding a very common default behavior for simple representations. No doubt, it’s going to become the preferred way to teach the basics of interactive D3.js visualizations.
Let’s look at the difference, using a very minimal dynamic barchart that is able to adapt based on the dataset changes.
Here the pre-join version (just the relevant part):
var rects = d3.select('svg') .selectAll('rect') .data(data) var newrects = rects.enter() .append('rect') .style('fill', 'red') rects.merge(newrects) .attr('width', d => d.value) .attr('height', 20) .attr('y', (d, i) => i*20) rects.exit() .remove()
Here, the same functionality with the new method:
d3.select('svg') .selectAll('rect') .data(data) .join('rect') .style('fill', 'red') .attr('width', d => d.value) .attr('height', 20) .attr('y', (d, i) => i*20)
Both handle the three different stages when a visualization needs to be updated according to a given dataset, in particular:
- a visual element needs to be created according to a new data-point (
- a visual element needs to be updated because its data-point has changed (
- a visual element needs to be removed because the data-point doesn’t exist anymore (
Here the complete Codepen, click on the chart to trigger the update:
You can check both versions here and here.
Well done, @mbostock.
Spotted a typo or (likely) a grammar error? Send a pull request.