D3.js explained in an image

Huy
The Full Snack Developer
3 min readMay 7, 2016

So, here is my attempt to explain D3.js in a visualized way:

1) What is D3.js?

2) Is it a chart drawing library? Yeah, kind of, but not really…

- But I want to draw chart!!!
- We will talk about this later! Keep calm and read on

3) It’s a DOM manipulating library.

4) Actually, it’s a Data-Driven DOM manipulating library

Wait! WTF is Data-Driven?????

5) Data-Driven is: Your data will determine how you will work with your DOM elements.

Okay… so how do we do that?

6) Let’s take a look at this:

var circle = svg.selectAll("circle").data(data);

circle.enter().append("circle").attr("r", 2.5);

circle
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });

The code above will draw some circles on the screen like this (just the circles, not the labels and axes):

Source: canvasjs.com

If you know nothing about D3, you still know (or you can guess):

  • selectAll() is a function to query all of the circle elements
  • data() is something to bind the data object to these circles

And what is enter(), what is d in the attr() function? Why do we selectAll() then append() a new circle? What will happen if there are no circle element to select?

Welcome to the most confused part of D3…

7) So, you can think that selectAll() is the same as jQuery selector, it return a list of matching elements on your screen.

data() function called right after selectAll(), it mean, we want to join our data with these elements.

8, 9a, 10) After this call, each element will be mapped with a record in your data. You are now able to manipulate the element.

circle
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });

In the code above, we manipulate cx and cy attribute of each circle elements. The second parameter of attr() function can be a value or an anonymous function with d is a data record that matched with this element.

8, 9b, 9c, 10) In case we found nothing in the selectAll(), the circle list now empty, or it has some data record that not joined with any element yet, D3 will allow us to call enter() function.

enter() function will join the new data record with the next call, which should be a call to add new element — append().

circle.enter().append("circle").attr("r", 2.5);

After created a new circle element, we can start manipulating it.

11) OK. Let’s talk about the chart.

12) This is actually how people are using D3 to draw chart: Create a new SVG element, create and join the geometrics with the data, drawing axes, add legends,…

And when you put them all together, you have the awesome working chart!

--

--

Huy
The Full Snack Developer

I write code, draw stuff. Currently interested in Machine Learning and Note Taking Techniques.