Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

JavaScript D3.js: Data-Driven-Documents in Practice

In this article, we are going to explore in practice all the main principles regarding Data-Driven-Document JavaScript framework, D3.js.

This article introduces you to the D3.js library. Here I would be covering the following topics with relevant and simple examples

  • Introduction to D3.js
  • History
  • Browser Support and Installation
  • Features
  • Basic Examples
    • Selections
    • Attributes/Styles
    • Data Binding
    • Append and Enter
    • Mouse Events
    • Transitions

Introduction to D3.js

D3, Data-Driven Documents, is a new visualization and JavaScript library. It provides an incredibly powerful toolkit for creating spectacular data visualizations in the browser. It uses digital data for creating and manipulating interactive graphical forms on web standards and provides all the capabilities of the modern browsers to the framework by combining data visualizations and data driven approach to DOM manipulation and is built on top of common web standards like HTML, CSS and SVG.

By using D3, designers bind the data to arbitrary document elements to generate and modify content by applying dynamic transforms.

One thing, here we have used the term data visualization. We may get data from resources such as social networking, shopping portals etc.., which is unstructured data. So this data cannot be used or visualized. We can convert this data into usable or understandable form. This method is known as data Visualization.

History

In the early 1990s, web browsers were capable of displaying static web pages only. The user can interact with web pages using links and scrollable pages. The only significant way was, use of JavaScript for web browsers which played an important role in D3.js. Some of the toolkits such as Prefuse, Flare and Protovis can be called as predecessors of D3.js.

  • Prefuse was a Java based toolkit for creating interactive visualization applications.
  • Flare was an ActionScript based toolkit and used a flash plug-in for working with applications.
  • In 2009, Ph.D student Mike Bostock and M.S student Vadim Ogievetsky created the Protovis JavaScript library to give more and better performance than Prefuse and Flare and was able to generate SVG graphics from the data.
  • In 2011, they stopped development of Protovis and focused on new project, D3.js. D3.js was developed in 2011 and version 2.0.0 was released in August 2011. Bostock, Ogievetsky and Heer developed expensive framework D3.js which provides improved performance. The stable release is version 3.5.3 and released on Dec 30, 2014 under BSD license.

Browser Support and Installation

IE8 and below do not support D3.js. It is supported by other modern browsers such as Mozilla Firefox, Google Chrome, Safari, Opera, Android, iOS and IE9+. If you want to work with D3.js library, then you need minimal requirements such as

  • JavaScript and
  • W3C DOM API.

D3.js is not a compatible layer. If you need your application to bemore interactive, your browsers need to have SVG and CSS3 transitions.

To install D3.js, you need to download the latest version 3.5.3 from the following link:https://github.com/mbostock/d3/releases/latest

Otherwise, you can add link directly in your code to make use of D3.js library as shown below:

<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>

Sometimes, there is chance of getting errors if you don’t serve D3 with UTF-8 encoding. This should be added at the top of the loading HTML page. The non minified source code contains non ASCII characters, so if you prefer a charset attribute on the script tag as charset= “utf-8” or else add < meta charset= “utf-8”> at the top of the page.

Features


  • It is a powerful and visualization library with tons of uses which bridge the gap between static data, and interactive and animated data visualizations.
  • As a JavaScript library, it helps to create spectacular visualizations.
  • It is data oriented and browser side library.
  • All data transformations and renderings are done at client side i.e. in the browser.
  • You can easily interact with D3.js using capabilities of web standards such as HTML, CSS and JavaScript events.
  • It provides support for large data sets and dynamic behaviors for interaction and animation.
  • It manipulates documents based on data.
  • It can be easily configured and composed by using JavaScript functions if we are familiar with HTML, CSS and JavaScript.

Basic Example

Here is a simple example where D3.js is used to display “Hello World” text on an empty document body.

Listing 1: HelloWorld.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>D3 Hello World Example</title>
    <script src="http://d3js.org/d3.v3.min.js"></script>
  </head>
  <body>
    <script type="text/javascript">
      d3.select("body").append("p").text("Hello World!!! Welcome to D3.js...");
    </script>
  </body>
</html>
                              

The above code uses D3.js to add a paragraph element to an empty document body with “Hello World” text. As mentioned earlier, there are chances of getting errors if you don’t serve D3 with UTF-8 encoding while loading the document, so you need to include charset= “utf-8” on the script tag or else add < meta charset= “utf-8”> at the top of the page. The d3.select() method selects only the first matching element and add paragraph element with Hello World text.

When we run the above script, we get following output:

Figure 1: HelloWorldExample

Selections

Selection is an array of elements pulled from the current document. The D3.js provides two types of selecting elements:

  • select : This method selects only first matching element
  • selectAll: This method selects all matching elements in the document.

d3.select(selector)

It matches the specified string and returns the single element. If it does not contain any element or if the current element does not match the specified selector, it returns an empty selection. If there are multiple elements that match the selector, then only the first matching element will be selected according to document traversal order.

Example

Here is the simple example demonstrating use of select() method:

Listing 2: SelectExample.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>D3 Select Example</title>
    <script src="http://d3js.org/d3.v3.min.js"></script>
  </head>
  <body>
  <p>Hello World!!!</p>
  <span>Welcome to D3.js...</span>
    <script type="text/javascript">
      d3.select("p").style("color", "red");
    </script>
  </body>
</html>
                                

As shown in the code, d3 selects the paragraph element which matches the specified selector and displays the element with color red.

When you run the script, you could see the below output in your browser:


Figure 2: SelectExample

d3.selectAll(selector)

It selects all the elements that match the specified selector. If it does not contain any element matching the specified selector, it returns an empty selection. The elements will be selected according to document traversal order i.e. top to bottom order.

Example

The following example is similar to above example, but the only difference is it selects all the elements in the document that matches specified selector.

Listing 3: SelectAllExample.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>D3 SelectAll Example</title>
    <script src="http://d3js.org/d3.v3.min.js"></script>
  </head>
  <body>
  <p>Hello World!!!</p>
  <span>Welcome to D3.js</span><br>
  <span>D3.js is a JavaScript library</span><br>
  <span>It  manipulates documents based on the data</span>
    <script type="text/javascript">
      d3.selectAll("span").style("color", "blue");
    </script>
  </body>
</html>

The code describes the selectAll () method. It selects all the elements that match the specified selector in the document.

When you run the script, you could see the following output in your browser:


Figure 3: SelectAllExample

Even you could select the elements by using class or id selector in the document. Consider the above example, you can write class name instead of span in the selectAll() method and class name should match the specified selector.

Here is an example using class selector:

Listing 4: SelectAllExample(ClassSelector).html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>D3 SelectAll Example</title>
    <script src="http://d3js.org/d3.v3.min.js"></script>
  </head>
  <body>
  <span>Hello World!!!</span><br>
  <span class="myfont">Welcome to D3.js</span><br>
  <span>D3.js is a JavaScript library</span><br>
  <span class="myfont">It manipulates documents based on the data</span>
    <script type="text/javascript">
      d3.selectAll(".myfont").style("font-family" ,"castellar");
    </script>
  </body>
</html>

When you run the above script, you will get second and fourth lines with different font for the elements which are matching with specified class selector name and we have set the font family property as a “castellar”.

Just run the code and you will get below output:


Figure 4: SelectAllExample(ClassSelector)

Attributes/Styles

By using D3.js, it is also possible to change attributes and styles of elements by using .attr() and .style() methods. These methods can be used to style SVG elements. The SVG stands for Scalable Vector Graphics, which is a text based image format. That means you can display SVG image by writing simple markup code and sort of like HTML tags. SVG can be included directly within the HTML document.

To use these methods, they have to be called on a selection.

The .attr() method can be written as follows:

selection.attr(“name”,”value”)

This method sets attribute with specified name to specified a value on the selected elements if and only if the value is specified. If you do not specify the value, then it returns the specified attribute for the first non null element in the selection.

The .style() method can be written as shown below:

selection.style(“name”,”value”)

You can set the CSS style property on the selected elements, if value is specified. If value is constant, then all elements will have the same style value.

Let’s see one simple example using these methods.

Listing 5: AttrandStyle.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>D3 Attribute and Style Example</title>
    <script src="http://d3js.org/d3.v3.min.js"></script>
  </head>
  <body>
        <p>This is example of attr() and style() methods</p>
        <svg width="100" height="100">
          <circle id = "myCircle" cx="50" cy="50" r="30" ></circle>
        </svg>
      <script type="text/javascript">
        var circleDemo = d3.select("#myCircle");
          circleDemo.attr("r", 40);
          circleDemo.style("stroke", "red");
          circleDemo.style("fill", "green");
      </script>
    </body>
  </html> 

As specified earlier, SVG is a text based image format and it is included in the HTML document. SVG is defined with height and width properties. It gives a basic shape using cx(center-x), cy(center-y) and r(radius) properties.

<circle id = "myCircle" cx="50" cy="50" r="30" ></circle>

To modify the circle, we need to create a selection and select “myCircle” and assign it to a variable called “circleDemo”.

circleDemo = d3.select("#myCircle");

The variable “circleDemo” is pointing to SVG circle element “myCircle” within the DOM.

circleDemo.attr("r", 40);

The attr() method is used to change the existing value and set new attribute value. It takes two values: the attribute to be changed and new value for the specified attribute. Here, “r” is the attribute to be changed and “40” is new value for the attribute which sets radius to 40 when the circle is drawn in the browser.

circleDemo.style("stroke", "red");

The style() method changes the styling of selected elements in the document. As CSS changes, D3 utilizes new changes without the need of patch. It also takes two values: the CSS style name to modify and value for that style. Here, “stroke” is like a border which sets the color as red. The one more style is “fill”. It is used to fill the color green in the circle.

When you run the script, the following output will get display:

Figure 5: AttrandStyleExample

Data Binding

Binding is like attaching or associating data to the specific elements. In D3, we can bind the data to elements in the DOM.

Normally if we want to store the values 1, 2, 3 and 4 in an array, we would store the array values in a variable as shown below:

var arrayDemo = [1, 2, 3, 4];

But D3 does not store the values within the variable. We use D3’s selection.data() method to store data within the DOM elements. The .data() method can be used by calling from a selector and passed an array of values.

The above array can be called as shown below:

selection.data([arrayDemo])

The array contains four values. So this point is executed four times, once for each value. The above line specifies two things: one is the data array and another one is the key function which assigns keys to the elements of the data array. The array of values combined with array of selections when the .data() method is called.

Consider we have 3 circles, which are created by using following code:

<svg>          
<circle cx="100" cy="60" r="30" style="fill:green;"></circle>
<circle cx="150" cy="60" r="30" style="fill:red;"></circle>
          <circle cx="200" cy="60" r="30" style="fill:purple"></circle>
</svg>

The code creates the three circles with values of cx, cy and radius r. Each circle filled with its respective as mentioned within the style attribute.

By using D3’s data binding, it is possible to change values by passing array of data. Let’s create one example using .data() method for changing the elements:

Listing 6: DataBinding.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>D3 Data Binding Example</title>
    <script src="http://d3js.org/d3.v3.min.js"></script>
  </head>
  <body>
     <div id="myexample">
       <svg>
               <circle cx="100" cy="60" r="30" style="fill:green;"></circle>
               <circle cx="150" cy="60" r="30" style="fill:red;"></circle>
               <circle cx="200" cy="60" r="30" style="fill:purple"></circle>
<circle cx="250" cy="60" r="30" style="fill: orange"></circle>
       </svg>
     </div>
     <script type="text/javascript">
               radiusVal=[10,15,20,25];
               selectExample=d3.select("#myexample");
               selectExample.selectAll("circle")
                         .data(radiusVal)
                         .attr("r", function(d) {return d});
     </script>
</body>
</html>

The code will create the four circles by using the data defined within SVG element. The idea which we are using to change the values elements uses .data() and .attr() methods.

radiusVal=[10,15,20,25];

The data is specified as array of values. The radiusVal is an array contains new radius for the circle elements. The first number 10 is bound to the first circle; the second number 15 is bound to the second circle and so on.

selectExample=d3.select("#myexample");

selectExample.selectAll("circle")

The first line is used to select the div element by using the id #myexample. We can select all the elements within selectExample which returns all the circles from within the selected div element using the selectAll() method.

data(radiusVal)

There are two methods for changing the elements. The .data() method will join the data to the selection and .attr() method take the joined data and used to change radius.

The D3.js iterates over array radiusVal using .data() method and returns the present values to the method. This method uses values of radiusVal with other method called .attr(). The present values in the radiusVal changes the radius of the circles. The each value from radiusVal called d is being passed to the method.

attr("r", function(d) {return d})

It sets the attribute that we want to change “r” and pass the new value by using the above anonymous function. We typically use the name d to refer to bound data.

When you run the above script, you would get the below output:

Figure 6: DataBindingExample

Append and Enter

The append() operator appends new element as last child of the element in the current selection. The append() method can be used to add selection, tag, container,

, ,


elements to the DOM.

The enter() method can be used to indicate new elements will be added to the current selection. It returns the virtual enter selection from the data operator.

Let’s create one example using these two methods:

Listing 7: AppendEnter.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>D3 Append and Enter Example</title>
    <script src="http://d3js.org/d3.v3.min.js"></script>
  </head>
  <body>
  <div id="myexample">
          <span>Hello World!!!</span><br>
          <span>Welcome to D3.js</span>
  </div>
  <script type="text/javascript">
          MyValues=[10,15,20,25];
          selectDiv=d3.select("#myexample");
          selectDiv.selectAll("span")
                    .data(MyValues,function(d) {return d;})
                    .enter()
                    .append("p")
                    .text(function(d) {return d;});
  </script>
  </body>
</html>

In the above code, you could see two statements written within the div element. These two statements will get displayed before the d3.js script is called. Let us go through with the script.

MyValues=[10,15,20,25] line specifies data specified as array of values.


selectDiv=d3.select("#myexample");
selectDiv.selectAll("span")

The first line is used to select the div element by using the id #myexample. We can select all the elements within selectDiv which returns an array of all span elements from within the selected div element using the selectAll() method.

data(MyValues,function(d) {return d;})

The .data() method contains data array and the key function which assigns keys to the elements of the data array. It specifies identity function as key function. The element 10 has a key of 10, 15 has key of 15 and so on. These keys won’t match any keys of elements in the existing selection which includes statements defined within span.

.enter().append("p")          .text(function(d) {return d;});

The .enter() method must follow .data() method call. This method uses current selection as parent node which are added with .append() method. Every new data element has different key and it is part of enter selection and added to the document when above methods are called. The .text() method adds members of the enter selection to the paragraph elements created by .enter. append (“p”).

When you run the above script, you would get the following output:

Figure 7: AppendEnterExample

Mouse Events

D3 can also be used to make some mouse events on the document. It uses the following syntax for mouse interaction:

selection.on(type[,listener])

The type is an event which uses various types of mouse events such as mouse over, mouse out, mouse click etc. The listener is triggered by the mouse event to perform specified action on the DOM element.

Consider one example:

Listing 8: MouseEvent.html

 <!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>D3 Mouse Events Example</title>
    <script src="http://d3js.org/d3.v3.min.js"></script>
  </head>
  <body>
        <p>This is example of Mouse Events</p>
        <svg width="100" height="100">
                              <circle id = "myCircle" cx="50" cy="50" r="30" ></circle>
        </svg>
      <script type="text/javascript">
            var circleDemo = d3.select("#myCircle");
                     circleDemo.attr("r", 40);
           circleDemo.style("stroke", "red");
                     circleDemo.style("fill", "gray");
                      circleDemo.on("mouseover", function(){d3.select(this).style("fill", "green");})
            circleDemo.on("mouseout", function(){d3.select(this).style("fill", "orange");});
      </script>
    </body>
  </html>

As we discussed earlier, SVG is a text based image format and it is included in the HTML document. SVG is defined with height and width properties. To modify the circle, we need to create a selection and select “myCircle” and assign it to variable called “circleDemo”. The attr() method is used to change existing value and set new attribute value as 40. The style() method changes the styling of selected elements in the document and “stroke” is like a border which sets the color as red and “fill” method fills the gray color in the circle.

The next two mouse events add event listeners for interaction. D3 selects the element and fill the green color on mouse over the element and orange color on mouse out of the element.

When you run the code, you could see the effects of mouse events as shown in the below output:

Figure 8: MouseEventExample

Transitions

The transition method is used to animate transitions when changing the DOM. It allows smooth rendering over time and also allows eye pleasant effect when updating the elements on the display.

It can be written as shown below:

d3.select (“this”).transition ();

For instance, you can change background color of the page by writing the line below:

d3.select("body").style("background-color", "lightblue");

Transition is used on selection to animate change over time; you need to add transition to selection as shown below:

d3.select("body").transition().style("background-color", "lightblue");

Consider the following example using transition () method:

Listing 9: Transition.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>D3 Transition Example</title>
    <script src="http://d3js.org/d3.v3.min.js"></script>
  </head>
  <body>
    <p>This is example of Transition Effect</p>
    <script type="text/javascript">
      d3.select("body").transition().style("background-color", "lightblue");
    </script>
  </body>
</html>

Run the above script, you would get below output:


Figure 9: TransitionExample

Transition are a form of Animation

We can animate elements by making use of transitions with two key frames: start and end. The starting key frame is current state of the DOM and ending key frame is a set of attributes, styles or any other properties you specify in the document.

We can set the starting value in the DOM before creating the transition.

For instance:

d3.select("body")
          .style("color", "green")
          .transition()
            .style("color", "red");  

It makes the text color as green before creating transition. When transition starts, text color would become red.

Let’s create the simple example by using the above code snippet:

Listing 10: TransitionAnimation.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>D3 Transition Example</title>
    <script src="http://d3js.org/d3.v3.min.js"></script>
  </head>
  <body>
    <p>This is example of Transition Effect</p>
    <script type="text/javascript">
      d3.select("body")
          .style("color", "green")
          .transition()
            .style("color", "red");
    </script>
  </body>
</html>

The above code displays the text color as red. When transition method activates, it makes the body color as green. When you refresh the page, you could see the change in text color as green.

When you run the code, you will see the below output:

Figure 10: TransitionAnimationExample

The life of transition has four phases:

· The transition is scheduled:

The transition is said to be scheduled when it is created. When selection.transition() method is called, it is called as we are scheduling the transition.

· The transition started:

When transition was scheduled, we can say transition is started. If there is no delay, then transition starts as soon as possible after few milliseconds.

· The transition runs:

When transition runs, it invokes the values with ranging from 0 to 1.

· The transition ends:

The transition is said to end when ending value is set to exactly 1.

Conclusion

Here we saw the main concepts which come under D3.js JavaScript library. D3.js is simple and reusable.

There are some key points, we must remember about D3.js:


  • It is an open source framework.
  • It is a JavaScript library.
  • It manipulates the document based on data.
  • It allows reuse of code.
  • It is compatible with all modern browsers.
  • We need to include the snippet below:


You can execute the attached source code of the above examples and play around to understand this JavaScript library better.



I''m a full stack developer with around 10+ yrs of experience. I enjoy writing technical articles on upcoming technical trends.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login