This chapter is from the book

Data-joins are the bread and butter of D3. If you take one thing away from this book, make it understanding how data-joins work and how to use them. Remember that D3 has no basic function for producing charts. Instead, it uses data-joins. This chapter covers how to use data-joins to add elements to a webpage and then manipulate them with data.

What Are Data-Joins?

As the name suggests, data-joins involve joining data with something. That something is an element or a number of elements on a web page—<rect>s, <circles>s, <div>s… all the usual suspects. More specifically, that something is a D3 selection of those elements.

Before we get into all of that, let’s take a few steps back. Forget about D3 for a second. Now, imagine an interactive graphic. It could be one you’ve seen somewhere or made yourself, or it could be one you invent in your mind right now. In this graphic there are shapes on the page that represent data and there are buttons for controlling what data is displayed. When you hit those buttons, the shapes change: their positions shift, they grow or shrink, they change color, or they can even fly off the screen altogether. Make it as crazy as you like.

Now, no matter how complicated or data-rich your graphic is, on a fundamental level, the shapes involved (or the lines, text, colors, or textures) only ever do one of three things:

Appear on the page in the first place—You can’t have a data visualization without both data and visuals, so the shapes need to show up.

Change—When you hit a button or adjust a slider, attributes of the shapes update to represent the new data you want to see.

Leave the page—Sometimes a shape or two will leave the page entirely, if the data that it represents is no longer relevant.

That’s it. Those three things. An interactive graphic is sort of like theater. During a play, actors enter the stage, they act, and they exit. In a data visualization, shapes, or more broadly, graphical elements, enter the page, they update, and they exit.

Data-joins take full advantage of this rudimentary idea. In using them, you can command graphical elements to enter, update, and exit. (In fact, I took the terms “enter,” “update,” and “exit” directly from D3.)

What’s more, D3 enables you to do all of these things based on data. The way it achieves this is through something called data binding. Whenever you perform a data-join, your data is actually connected, or bound, to elements. This is hugely convenient, because D3 gives you easy access to bound data. So you can say, for example, “Okay rectangle, what does your bound data point say? 35? Well, that’s what I want your width to be!”

This probably only makes vague sense at this point. Don’t worry, we’ll go through everything slowly and in detail, using an example as a guide. This chapter will focus just on enter, and in Chapter 8, we’ll cover update and exit.