Getting Started With Visualization D3 JS Chart

Introduction

D3js chart is free, open source, and built on top of HTML5 Standard. As per the official website,  D3 allows you to bind arbitrary data to a Document Object Model (DOM), and then apply data-driven transformations to the document. For example, you can use D3 to generate an HTML table from an array of numbers. Or, use the same data to create an interactive SVG bar chart with smooth transitions and interaction.

Description

Here we learn basic usage of D3js and then moved to different type of visualization chart.

  1. How Selections works

    Modifying documents using the W3C DOM API is tedious,

    For example, to change the text color of paragraph elements:
    1. var paragraphs = document.getElementsByTagName("p");  
    2. for (var i = 0; i < paragraphs.length; i++) {  
    3. var paragraph = paragraphs.item(i);  
    4. paragraph.style.setProperty("color""white"null);  
    5. }  
    D3 uses new W3C Selectors API and supported natively by modern browsers. Elements may be selected using a variety of predicates, including containment, attribute values, class and ID. You can rewrite above code as below in single line:
    1. d3.selectAll("p").style("color""white");  
    D3 provides numerous methods for mutating nodes: setting attributes or styles; registering event listeners; adding, removing or sorting nodes; and changing HTML or text content.These operators can get or set attributes, styles, properties, HTML and text content.

    I have implemented a demo for selector example in jsfiddle.

    Here is a different way to use selector and append new element

    a. d3.select(selector)

    Select first element which matches to selector and selector varies to tag,class,id etc. If no elements in the current document match the specified selector, it returns the empty selection.This function traverses the DOM in top to bottom order.

    b. d3.select(node):

    Select specified node.This is useful if you already have a reference to a node, such as d3.select(this) within an event listener.This function does not traverse the DOM.

    c. d3.selectAll(selector):

    Select all elements which match to selector. If no elements in the current document match the specified selector, returns the empty selection.This function traverse the DOM top to bottom order.

    e.g.
    1. d3.selectAll("P");   
    2. d3.selectAll(".someclass>p");  
    d. d3.selectAll(node):

    Select specified elements of array. This is useful if you already have a reference to a node, such as d3.selectAll(this.childNodes) within an event listener. This function does not traverse the DOM.

    Selection also works with chaining method, this applied multiple operations to same elements. Let's see example.

    e.g. Here first we have select all p tag and then set text color and background color.
    1. d3.selectAll("p"  
    2. .style("color","blue")   
    3. .style("background-color","yellow");  
    For more information you can refer this.

  2. Dynamic Properties

    D3 provides many built-in reusable functions and function factories, such as graphical primitives for area, line and pie charts.

    For example, to randomly color paragraphs:
    1. d3.selectAll("p").style("color", function() {  
    2. return "hsl(" + Math.random() * 360 + ",100%,50%)";  
    3. });   
    4.   
    5. To alternate shades of gray for even and odd nodes:   
    6.   
    7. d3.selectAll("p").style("color", function(d, i) {  
    8. return i % 2 ? "#fff" : "#eee";  
    9. });  
    Computed properties often refer to bound data. Data is specified as an array of values, and each value is passed as the first argument (d) to selection functions.

    With the default join-by-index, the first element in the data array is passed to the first node in the selection, the second element to the second node, and so on.

    For example, if you bind an array of numbers to paragraph elements, you can use these numbers to compute dynamic font sizes:
    1. d3.selectAll("p")  
    2. .data([4, 8, 15, 16, 23, 42])  
    3. .style("font-size", function(d) { return d + "px"; });  
    You can test this code in jsfiddle by changing selector.

  3. Enter, Update and Exit

    Using D3’s enter and exit selections, you can create new nodes for incoming data and remove outgoing nodes that are no longer needed.

    When data is bound to a selection, each element in the data array is paired with the corresponding node in the selection. If there are fewer nodes than data, the extra data elements form the enter selection, which you can instantiate by appending to the enter selection.

    For example:
    1. d3.select("body").selectAll("p")  
    2. .data([4, 8, 15, 16, 23, 42])  
    3. .enter().append("p")  
    4. .text(function(d) { return "I’m number " + d + "!"; });  
    Updating nodes are the default selection—the result of the data operator. Thus, if you forget about the enter and exit selections, you will automatically select only the elements for which there exists corresponding data.

    A common pattern is to break the initial selection into three parts: the updating nodes to modify, the entering nodes to add, and the exiting nodes to remove.
    1. // Update…  
    2. var p = d3.select("body").selectAll("p")  
    3. .data([4, 8, 15, 16, 23, 42])  
    4. .text(function(d) { return d; });  
    5. // Enter…  
    6. p.enter().append("p")  
    7. .text(function(d) { return d; });  
    8. // Exit…  
    9. p.exit().remove();  
    By handling these three cases separately, you specify precisely which operations run on which nodes. This improves performance and offers greater control over transitions.

    For example, with a bar chart you might initialize entering bars using the old scale, and then transition entering bars to the new scale along with the updating and exiting bars.

    D3 lets you transform documents based on data; this includes both creating and destroying elements. D3 allows you to change an existing document in response to user interaction, animation over time, or even asynchronous notification from a third-party.

    A hybrid approach is even possible, where the document is initially rendered on the server, and updated on the client via D3.

    You can learn more from this article.

  4. Transformation, not Representation

    D3 does not introduce a new visual representation. Unlike Processing, Raphaël, or Protovis, D3’s vocabulary of graphical marks comes directly from web standards: HTML, SVG, and CSS. For example, you can create SVG elements using D3 and style them with external stylesheets.

    You can use composite filter effects, dashed strokes and clipping. If browser vendors introduce new features tomorrow, you’ll be able to use them immediately—no toolkit update required.

    And, if you decide in the future to use a toolkit other than D3, you can take your knowledge of standards with you!

    Best of all, D3 is easy to debug using the browser’s built-in element inspector: the nodes that you manipulate with D3 are exactly those that the browser understands natively.

  5. Transitions

    D3’s focus on transformation extends naturally to animated transitions. Transitions gradually interpolate styles and attributes over time. Tweening can be controlled via easing functions such as “elastic”, “cubic-in-out” and “linear”.

    D3’s interpolators support both primitives, such as numbers and numbers embedded within strings (font sizes, path data, etc.), and compound values. You can even extend D3’s interpolator registry to support complex properties and data structures.

    For example, to fade the background of the page to black:
    1. d3.select("body").transition()  
    2. .style("background-color""black");  
    Or, to resize circles in a symbol map with a staggered delay:
    1. d3.selectAll("circle").transition()  
    2. .duration(750)  
    3. .delay(function(d, i) { return i * 10; })  
    4. .attr("r", function(d) { return Math.sqrt(d * scale); });  
    By modifying only the attributes that actually change, D3 reduces overhead and allows greater graphical complexity at high frame rates. D3 also allows sequencing of complex transitions via events. And, you can still use CSS3 transitions; D3 does not replace the browser’s toolbox, but exposes it in a way that is easier to use.

    Reference link: https://github.com/mbostock/d3/wiki

Conclusion

In this article we have learned basic concepts of D3 charting and feature. In next series of article we learn real chart examples with customization.

Read more articles on Open Source Technologies: