Introduction to D3.JS

D3.js is a javascript library to render the amazing charts based on data. It can be used to visualise the stats and finding the patterns, showing the comparison between two or more time-series data, drawing the data in real time as it happens (for e.g. data generated by various sensors or internet traffic) and even to create cool dynamic art on webpages. It just depends on one’s imagination how s/he can use this library. To view a huge catalogue of charts drawn by this library one can visit the official website of D3.js.

D3 is not a pre-built library composed of particular charts, instead it’s a tool that can be used to create various charts (actually any chart one can envision). It uses SVG (Scalable Vector Graphics) to draw the charts along with HTML and CSS. With D3 a dataset of 10’s of thousands objects can be represented graphically easily. If you design your custom chart and you want to use some part of that , a module, in other charts then you can also create a module to reuse in other projects.

One can quickly start coding the D3 charts with HTML by including the script source in between tags. The latest version at the time of writing this blog is V4.

<!doctype html>
        [script src=""] [/script]
        <!-- HTML and Js code -->

Selecting and Appending with D3

If you’ve used a library like jQuery then selecting an element is gonna be easy for you, but even if you are starter in JS world just because others told you that JS is daemon then take a chill pill, it’s gonna be super easy for you. One doesn’t need to know a greater depth of JS and by the end of your voyage through D3 your comprehension of JS will be drastically enhanced.

<!doctype html>
  [script src=""] [/script]
  <p>This is a paragraph.</p>

      .style("color", "blue");

This code above is the simplest it could be. Here the most important thing in this whole code is the d3 object. d3 object is a big and complex object that has all the functionalities of the d3.js library. If you want to look inside it then after loading your .html code in browser open the browser console by pressing Ctrl + Shift + i. Type d3 in console and hit the enter. You will see all the components of the d3.

Now back to our example, with select() method of d3 object any DOM element can be selected and after doing that some operation can be performed on it. Here the <p> element is selected and its colour is changed to blue.

<!doctype html>
  [script src=""] [/script]
        .text("Hi! What's up!!")
        .style("color", "blue");

This time we selected the body and and appended a paragraph with blue text.

But D3 is not created to do these tasks as libraries like jQuery already do that. The core use of D3 is to draw the SVG elements on webpage and playing with them in order to create dynamic and interactive charts. In the next post more SVG elements will be drawn and data will be rendered graphically on a webpage.

Drawing Basic Shapes with D3

Let’s start with creating the basic shapes in D3. But we can’t do that just by adding the SVG shapes directly to the HTML page, SVG shapes require an SVG container. All the shapes inside that container can be relatively adjusted henceforth for e.g. change in one curve effecting the another curve or changes in coordinates changing the shapes of curves or positions of points inside that container.

We can add the container to the body of HTML page with append() method. And then adding shapes to that container. Here the container is 600px wide and high.

var canvas ="body")
                   .append("svg")         //SVG container
                   .attr("width",  600)   //Width of the container
                   .attr("height", 600)   //Height of the container

var circle = canvas.append("circle")
                    .attr("cx", 250)      //Circle at the (250,250) coordinates
                    .attr("cy", 250)
                    .attr("r", 60)        //Radius of the circle is 50px
                    .attr("fill", "green")//Fill the circle with red color

var rect = canvas.append("rect")           // By default the shapes are drawn from upper left
                   .attr("width", 300)     //corner of the SVG container
                   .attr("height", 100)
                   .attr("fill", "red");

var line =canvas.append("line")
                   .attr("x1", 0)
                   .attr("y1", 40)
                   .attr("x2", 400)
                   .attr("y2", 400)
                   .attr("stroke", "yellow")
                   .attr("stroke-width", 10);


Binding data with visualisation

After learning to draw the basic shapes in D3 we need to draw the meaningful curves on the screen which are influenced by the data. To do that we need to bind the data with DOM elements that can visually represent the data in any form (bar chart, pie chart, histogram, geographical graphs etc) whatever a programmer wants to. In real world the actual data is large and most probably in a JSON or CSV file, but here for demo purposes data is taken in the array of some elements.

var dataArray = [60, 25, 45, 30];

This data array will be used to draw a simple histogram. The process of drawing a histogram is explained line by line. The below code is assumed to be inside the <script> tags.


var array = [60, 25, 45, 30];

var canvas ="body")
                 .attr("width", 600)
                 .attr("height", 600);

var bars = canvas.selectAll("rect") //Empty selection
                   .enter() //This method holds the placeholder for array elements
                     .attr("width", function(d) { return d*10; })
                     .attr("height", 50)
                     .attr("y", function(d, i) { return i * 51 })

The code written for bars is of more significance, as now it is known how canvas is attained. The line canvas.selectAll(“rect”) is a little confusing because there is no DOM element named rect to make a selection. What this line does is returning the empty selection which can be used to draw individual bar for our histogram. The .data() method binds our data to whole selection. To fill each bar of histogram each element of the array is bind to one empty selection,  and it is done by the .enter() method. Though there is more to explain about the .enter() method, but for now just go with the flow. After binding each element of the array with empty bar selection we give shape to our bars with width and height attributes. For width we can use a fixed value but that behaviour won’t work for for us because we want to give width to each bar based on data element. To do that the anonymous function is passed with the element from array and it returns back the width of an individual bar. The height of the bars is fixed. The attribute  is really interesting because if not given all the bars will lie over each other. This y attribute gives the vertical position of the bar relative left upper corner of the canvas.

So now the pretty basic introduction of D3.js is done. Code it and see the results in your browser. Till the next blog post is out about D3.js, go through the sample code of different charts on official website of D3 to get familiar with D3 charts’ code.

About Ashish

Software Consultant at Knoldus Software LLP, Noida (India)
This entry was posted in Scala and tagged , . Bookmark the permalink.

2 Responses to Introduction to D3.JS

  1. Pingback: Introduction to D3.js {Part -2} | Ashish Tomer

  2. Pingback: Introduction to D3.js {Part – 2} | Knoldus

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s