Contents

How to Use Selections and Data Joins in D3.js?

Suppose that you want to display several shapes aligned regarding to a list of data that defines the position of these shapes. In this post we will see how to use selections and data joins in D3 to display aligned circles using specific data. You should know how circles work in D3 before reading this article (see: https://www.datackling.com/post/how-to-draw-a-circle-in-d3-js ).

Introduction

For the example we use this list of data: const data = [40, 30, 20, 10, 20, 30, 40]

We will display aligned circle which the x position depends on the list above.

Let’s append a general svg object in the window:

const svg = d3.select("#canvas").append("svg").attr("width", 100).attr("height", 100);

Selections

Now we will select all the circles on the screen and join the data to the selection.

const circles = svg.selectAll("circle").data(data);

We pass the result of the snippet above on the enter() method, then we append a circle with basic attributes.

circles.enter().append("circle").attr("cx", 50).attr("cy", 50).attr("r", 25).attr("fill", "blue");

Now, for each new circle we can manage attributes using functions. Let’s do it.

For this example we will modify the x position and the radius using the data above.

1
2
3
4
5
circles.enter().append("circle")
.attr("cx", (d, i) =>  (i*50)+50)
.attr("cy", 200)
.attr("r", (d) => d)
.attr("fill", "blue");

We define the x position with multiplying the index in data by 50 and adding 50 pixels. We define the radius with the value in the data.

Finally, you should get this result: As you can see it is very simple to use function to modify dynamically the attributes of a shape in D3. This post is about very basic stuff, but in future we could make dynamic and interactive charts with this method.

I hope you enjoyed this post. Feel free to ask your questions in DM. See you!