A Beginner’s Guide to Data Binding in D3.js

D3.js is a powerful data visualization library that allows you to create amazing charts — such as bubble charts, line and bar charts — with just a few lines of code.

With a beginner’s understanding of JavaScript, you can convert your array or object into a colorful display. However, every single beginner struggles at first to understand how data is tied to actual elements in the DOM. This is known as “data binding” or “data joins”. It’s a huge deal, because it’s the first step of the entire process!

Intuitively, you might expect a for() loop, where you loop over every item in your data and create an element. Like this:

[code]var data = [{x: 100, y: 100}, {x: 200, y: 200}, {x: 300, y: 300}]

for(var i=0; i< data.length; i++){
svg.append(“circle”)
.attr(“cx”, function(data) { return data[i].x; })
.attr(“cy”, function(data) { return data[i].y; })
.attr(“r”, 2.5);
}
[/code]

But this isn’t how it works! In fact, there are no for() loops involved at all. Instead, here’s the code block that would cover the functionality above:

[code]var data = [{x: 100, y: 100}, {x: 200, y: 200}, {x: 300, y: 300}]

svg.selectAll(“circle”)
.data(data)
.enter().append(“circle”)
.attr(“cx”, function(d) { return d.x; })
.attr(“cy”, function(d) { return d.y; })
.attr(“r”, 2.5);
[/code]

This would add 3 black circles to your SVG canvas. Whoa. This is because D3 uses a declarative style of programming. The for() loop is covered implicitly in this code block.

This takes some getting used to, so I’m going to go through the code block above line-by-line so you can understand exactly what’s going on. It’s the same idea as planting a vegetable garden. When you’re done reading, you’ll be able to build any basic visualization in 5 to 10 lines and get started with styling (the easy part).

If you’re looking for a more technical explanation of this concept, check out the D3 documentation or Scott Murray’s guide to data binding.

Step 1: SVG/ The Plot of Land

First, you need to choose where you want to draw the data visualization. This is equivalent to choosing the area you want to plant:

[code]>var svg = d3.select(“body”)
.append(“svg”)
.attr(“width”, ‘800px’)
.attr(“height”, ‘800px’);
[/code]

This creates an 800px by 800px area of land — the body — into which you can add your elements. Pretty straightforward.

Empty plot

Continue reading %A Beginner’s Guide to Data Binding in D3.js%


Source: Sitepoint