Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Introduction to D3.js

DZone's Guide to

Introduction to D3.js

D3.js is an important analytics tool for dynamic, interactive data visualizations in web browsers. Read on to learn more about D3.js and how to quickly start coding it.

· Web Dev Zone
Free Resource

Should you build your own web experimentation solution? Download this whitepaper by Optimizely to find out.

D3.js is a JavaScript library used to render amazing charts based on data. It can be used to visualize stats and find patterns, show the comparison between two or more time-series data, draw the data in real-time as it happens (for example, data generated by various sensors or internet traffic), and even create cool dynamic art on web pages. How you use this library just depends on one’s imagination. To view a huge catalog 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 — any chart you can envision). It uses SVG (Scalable Vector Graphics) to draw the charts along with HTML and CSS. With D3 a dataset of tens of thousands of objects can be represented graphically easily. If you design your custom chart and you want to use 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>
<html>

<head>
    [script src="http://d3js.org/d3.v4.min.js"] [/script]
</head>

<body>
    <!-- HTML and Js code -->
</body>

</html>

Selecting and Appending With D3

If you’ve used a library like jQuery, then selecting an element will be easy for you. If you are just a beginner in the JS world, then relax — it’s gonna be super easy for you. You don’t need to know a lot of JS, and by the end of your voyage through D3, your comprehension of JS will be drastically enhanced.

<!doctype html>
<html>

<head>
    [script src="http://d3js.org/d3.v4.min.js"] [/script]
</head>

<body>
    <p>This is a paragraph.</p>

    [script] d3.select("p") .style("color", "blue"); [/script]
</body>

</html>

The code above is the simplest it could be. Here, the most important thing in this whole code is the d3 object. The 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 the browser, open the browser console by pressing Ctrl +Shift+i. Type “d3” in the console and hit Enter. You will see all the components of the d3.

Now back to our example. With the select() method of thed3  object, any DOM element can be selected. After doing that, some operations can be performed on it. Here, the <p>> element is selected and its color is changed to blue.

<!doctype html>
<html>

<head>
    [script src="http://d3js.org/d3.v4.min.js"] [/script]
</head>

<body>
    [script] d3.select("body") .append("p") .text("Hi! What's up!!") .style("color", "blue"); [/script]
</body>

</html>

This time, we selected the body 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 the web page 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 web page.

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 example, change in one curve affecting 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 the append() method and then adding shapes to that container. Here, the container is 600px wide and high.

var canvas = d3.select("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 Visualization

After learning to draw the basic shapes in D3, we need to draw meaningful curves on the screen that 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.). In the 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 = d3.select("body")
               .append("svg")
                 .attr("width", 600)
                 .attr("height", 600);

var bars = canvas.selectAll("rect") //Empty selection
                   .data(array)
                   .enter() //This method holds the placeholder for array elements
                     .append("rect")
                     .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. This line returns the empty selection, which can be used to draw individual bars for our histogram. The .data() method binds our data to whole selection. To fill each bar of the histogram, each element of the array is binded to one empty selection, and it is done with the .enter() method. 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 the empty bar selection, we give shape to our bars with width and height attributes. For width, we can use a fixed value, but that behavior won’t work for for us because we want to give width to each bar based on the data elements. To do that, the anonymous function is passed with the element from the array and it returns the width of an individual bar. The height of the bars is fixed. The attribute y 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 upper-left corner of the canvas.

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

Implementing an Experimentation Solution: Choosing whether to build or buy?

Topics:
data visualization ,big data ,d3.js ,javascript ,tutorial

Published at DZone with permission of Ashish Tomer, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}