A beginner's guide to using D3 to do data binding

Source: Internet
Author: User

A beginner's guide to using D3 to do data binding

D3.js is a powerful data visualization library that can make stunning charts. For example: Bubble chart, line chart and bar chart--only a few lines of code are needed

With the beginner's understanding of JavaScript, you can convert an array or object into a colorful display. However, the comparison of each beginner is the beginning of understanding how to bind data to actual DOM elements. This is what we know about "data binding" or "data connection". This is an important deal because this whole process is the first step!

Very intuitive, you might want to use a for () loop, loop through each item of data, and create an element like this:

    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);    }

However, this does not say how to make it work, in fact, there is no for () loop, the following code block will overwrite the above features:

    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(data){ return data[i].x;})            .attr("cy",function(data){ return data[i].y;})            .attr("r",2.5);

This code adds 3 black circles to your SVG cancas, wow, because D3 uses declarative programming and the for () loop is implied in this block of code.

This article will be used for getting started, so I'll explain the code block line above, so that you can fully understand how the code works. I think it can be likened to a vegetable plantation. When you finish reading this article, you will be able to create a basic visual view that uses 5 to 10 lines of code.

If you're looking for more technical notes on this concept, check out the D3 documentation or Scott Murray's guide-to-binding

First step: svg/plots

First, you need to choose a place to draw your visual attempt. This is equivalent to looking for a place to grow.

    var svg=d3.select("body")      .append("svg")      .attr("weight",‘800px‘)      .attr("height",‘800px‘);

You create a 800px * 800px plot--This "body"--a place where you can add elements. Quite simple.

Step Two: Selectall/Burrows

Next, we need the SelectAll () statement to create a group that will be populated with elements later. Imagine, it's like digging a hole in your garden. D3 can update or remove the entire element group, which is an example:


If you do not add any circles, then this is normal, note that "circle" is a basic shape in SVG specification, and if you add a circle, you can choose to use the class name, like this:


This picture is not very accurate, because you can have countless holes in your garden. There is no good way to use a picture to explain the amount of space. The most important thing is that you plan an area and put it into your data elements. If you want to add the SVG "rectangle" element. You will add in another part of your garden. At this point in the code, you don't know how many elements you're going to add. Let's get this straight.

Step three: data/seeds

This is the most important part. It determines the data that you will use for visualization. In JavaScript, you can pass data through arrays or objects, where you "bind" your data on DOM elements, and the type of DOM elements you specify in SelectAll (). You can refer to an array or a child of an object in the same way as you normally would in JavaScript. In this example, there are three subkeys in the array, and when we finish writing the following code, we want to have three DOM elements added:

    var data = [{x: 100,y: 100},{x: 200,y: 200},{x: 300,y: 300}]    svg.selectAll("circle")        .data(data)

It's much like choosing a particular type of seed to plant in your garden. Each type of seed has certain characteristics, and we know the type of these seeds.

Fourth step: enter/the seeds into the hole.

The. Enter () method matches the number of children of an array or object in a SelectAll statement, and determines the number of elements you need to create. You no longer have an infinite land. The number of holes now matches the number of plants you want to plant:

    svg.selectAll("circle")        .data(data)        .enter()

In this example code, there are three pits, and the seed is a specific type (e.g. potatoes), which also determines how many times your code will automatically iterate (3 times)

Fifth step: The structure of append/plants

The. Append () method determines which SVG basic shape you use, although you have many options in the SelectAll () statement, but in this step you have only 7 shapes to choose from. SelectAll () is named for a group, and append () is named as the actual shape.

    svg.selectAll("circle")        .data(data)        .enter().append("circle")

This is similar to the structure of your plant, what do you want your plant to look like? If you want to grow tomatoes, you need a tower, different shapes and different data visualizations are available for different datasets.

A brief description of how to access the data

Well, now that you've added the 3-circle DOM element, you've chosen your land, dug a hole, planted the seed and provided the structure of the plant's growth. Here's how to select the properties for each circle:

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

According to the specification of the circle, we know that we can use the SVG canvas to determine the position of the circle using CX and CY, in the example above, we use function (d) to access each subkey in the first array until we use the. Enter (), This block of code runs once for each element in the array, running three times in total.

This d parameter represents each element in the array, such as: {x:100, y:100}, if the argument is in the form of d,i, this I is the index of the array, when it is 0 refers to the first element in the array, 1 o'clock refers to the second element, and so on. When you call it d.x, you are looking at the x attribute of each element and turning the corresponding value into a pixel, in our case it is 100 pixels from the right, and now you are using the usual javascript! You can use the IF statement, call function, and so on some other.


When you use D3 to build cool stuff, you need to understand the specific method you choose to convert the data into DOM elements, which is relatively simple compared to the data. Adding text is particularly similar to adding shapes, and once you understand this part of the data, you will also understand the text.

Although you might D3 creators to add such challenging concepts to the early learning process, they have good reasons to do so. D3 is a flexible library, you can approach the automatic processing of many challenges, this data binding structure can help you to complete complex operations, only need one or two lines of code, now go to amaze your users!

A beginner's guide to using D3 to do data binding

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.