Data Joins/Binding

Learn about data joins and the methods used for data joining.

We'll cover the following

Introduction

Data joining is a fundamental concept in D3.js, and it allows us to bind the data of an array with each element, HTML or SVG (we will cover it in the next chapter) selection.

It binds data with selection elements and makes the manipulation of elements based on data much easier. We will use data binding throughout the course to draw different visualizations.

There are two methods that are used to bind data to a D3 selection which are explained below:

datum()

Let’s explore the first method. The datum() method joins data points with a single D3 selection. See the following example for a better understanding.

datum() method code

In the above example, we want to bind the data element with the HTML tag. In line 1, we select the p tag using the select() method. Then, in line 3, the datum() method is used to bind 10 with the p tag. In line 4, text() is used to return the data associated with the p tag.

What will happen if we want to associate multiple data points with selections in one go? To answer this question, let’s take a look at another data binding method, i.e., data().

Data()

If we want to associate a set of data points with a set of D3 selections then we will use the data() method. To better understand how this works, let’s take a look at the following example.

Data() method code

In this example, we have three data points and we are combining them with multiple D3 selections, in this case, three p tags. Multiple data joins are done with help of the data() method in line 2.

What will happen if the number of data points in the array is greater than the number of D3 selection elements? That’s where we will use the enter() method.

enter()

The enter() method is used when the number of elements in D3 selection is less than the number of elements in the data array. See the following example to understand the working of the enter() method.

enter() method code

In the above example, we have three D3 selections that are p tags, as we can see in the HTML file, and five data elements in the array. To create new p tag elements and bind every data element with the selection element, we used the enter() method in line 4.

In line 5, we append a new p tag for every missing data element using the append() method.