Getting started with d3js Data Binding

Source: Internet
Author: User

Introduction

D3js is an easy-to-use JS class library dedicated to drawing SVG graphics and charts. Its key concept isData-joinThis concept is very important to understand. It will reflect data-driven programming in a concise and elegant form.

The following is the slogan of thinking with joins. The original author is Mike Bostock.

Suppose you want to use D3 to draw a scatter chart, so you need to generate some SVG circle elements to visually display the data. you will be surprised to find that D3 does not provide native interfaces to generate multiple DOM elements,

Yes, there is only one append method for generating a single Dom element:

svg.append("circle")    .attr("cx", d.x)    .attr("cy", d.y)    .attr("r", 2.5);

But it is only a single circle, and you want more: it is better that each element in data * corresponds to a circle. let's look at an example in D3 before you draw the circle with a write loop of brute force:

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

* HeredataIs
JSON array, each element of which is composedxAndyAttribute composition,
For example:[{"x": 1.0, "y":1.1},{"x": 2.0, "y":2.5},
…]
In addition, the SVG circle element uses CX and Cy to express the Center Coordinate, and r to express the radius length.

This Code meets your needs, that is, each element generates a circle throughxAndyThe property represents the coordinates of the center.


HoweverSelectall ("circle ")What does it mean,Why should we select an element that does not exist before all circles are generated?


The original thing was like this: Tell D3 your goal, instead of telling it how to do it.
In this example, D3 knows that our intention is to let the selected "circle" element respond to data changes,
Selectall describes this goal, without the need to step-by-step command D3 to generate multiple circles.This concept isData-join.


Perform the following steps behind data-join:

  1. selectAll("circle")An empty selection is returned.
  2. Empty selection is passedThe data () method binds the data to the DOM element.And generate three virtual subsets:Enter,UpdateAndExit.Enter() The method contains the data to be added and the placeholder of the corresponding Dom element;Update ()Contains existing elements bound to the data. The remaining elements to be removed are included inExit() Method
  3. The result of the initial selection is empty. Therefore, all data is to be added and appears inIn the result of enter.
  4. No cycle is required.. Enter (). append ("circle") to add the elements to the SVG container at one time.

Why is it so troublesome? Why not directly provide native interfaces? The elegance of data-join lies in abstraction and decoupling. The above Code only concentrates on the new elements in the enter (), whileUpdateAndExitFocus on processing updates and pending deletions respectively. this means that you do not need to delete all the DOM elements, so you can easily cope with real-time changes in data, and even support some interaction (such as drag) and gradient effects!

Here is an example of processing three States (adding, modifying, and deleting:

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; });circle.exit().remove();

If we run the code repeatedly, it recalculates data-join every time. if the new dataset is smaller than the original one, extra elements will appear in exit and be removed. and vice versa. The new data appears in enter (), and the DOM element is added through append. if the size of the new and old data sets remains the same, all data is the update coordinate. <G id = "1"> Update () </G> is called implicitly)

Thinking in the form of joins makes your code more intuitive: the code that processes these three states does not require conditional (IF) and loop (for) branches, you only need to briefly describe how to make the image respond to data changes. if the selection result of a given enter, update, or exit is null, the corresponding code block is automatically skipped to reduce performance overhead.

Joins supports operations in a specific State (add, delete, or modify). For example, you can specify static attributes (such as the circle radius,"r"Attribute specified)
. Depending on precise modification of target elements and minimal Dom changes, you have greatly improved the rendering performance of your browser! Similarly, you can show gradient and other animated effects in a specific State. For example, the newly added circle can be changed from none (the radius ranges from 0 to 2.5 ):

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

The circle to be deleted can also gradually contract until it disappears:

circle.exit().transition()    .attr("r", 0)    .remove();

I believe you have learned how to use joins to think about it!

Related Article

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.