Updating your chart

Updating your d3 chart used to be a bit confusing for most people.

The data pattern takes some time to understand properly and when I teach d3 courses people always got trip up on it.

But d3 version 5 just made it a whole lot easier to use and understand.

There is a new method: join And with it we don’t need to use enter and exit directly anymore. These were the methods with the most confusion.

But you still can use them. You pass them to the join method to have more fine grain control.

Let‘s take a look at how it works.

Before:

circles = d3.select('svg').selectAll('circle').data([1,2,3,4])
circles.enter().append('circle')
circles.exit().remove()
circles.merge().attr('r', (d) => d)

After

circles = d3.select('svg').selectAll('circle').data([1,2,3,4])
circles.join('circle').attr('r', (d) => d)

What? Pretty great, right? That means less boilerplate code. I used to write the enter, append, exit, remove code a lot of times. So it‘s great that this is now gone. The join method will call append and remove internally.

But what if you want to animate the remove? You still can. It‘s just a little different:

circles = d3.select('svg').selectAll('circle').data([1,2,3,4])
circles.join(
  enter =>   
    enter.append('circle').attr('fill', 'green'),   
  exit => exit.attr('fill', 'brown').call(
    exit =>   
      exit.transition(svg.transition().duration(750))
    .remove()
    )
)

This looks a little crazy. But is kinda genius. The uses-cases for these animations and changes are rare, so most people will benefit greatly from this change and the others just need to learn a little bit different syntax.

See Also

Projections

Learn all the things that are important about projections in d3.

How to create a simple tooltip in d3.js

Learn how to create tooltips in d3. This post shows you actual d3 code and adds explanations to the most important aspects of tooltips in d3 and has a demo as well.

SVG Basics for d3

Three basic elements of SVG you should know if you want to create maps with d3.