You are on page 1of 16

Unit- 4

Introduction to D3.js:
D3:
D3 stands for Data-Driven Documents. D3.js is a JavaScript library for manipulating documents
based on data. D3.js is a dynamic, interactive, online data visualizations framework used in a large
number of websites.
D3 combines powerful visualization and interaction techniques with a data-driven approach to
DOM manipulation, giving you the full capabilities of modern browsers and the freedom to design
the right visual interface for your data.
D3 helps you bring data to life using HTML, SVG, and CSS. 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.
D3 is not a monolithic framework that seeks to provide every conceivable feature. Instead, D3
solves the crux of the problem: efficient manipulation of documents based on data. This avoids
proprietary representation and affords extraordinary flexibility, exposing the full capabilities of
web standards such as HTML, SVG, and CSS.
With minimal overhead, D3 is extremely fast, supporting large datasets and dynamic behaviors for
interaction and animation. D3’s functional style allows code reuse through a diverse collection of
official and community-developed modules.

Getting Set Up with D3:


We need to include the D3.js library into your HTML webpage in order to use D3.js to create
data visualization. We can do it in the following two ways −
1. Include the D3.js library from your project's folder.
2. Include D3.js library from CDN (Content Delivery Network).

Download D3.js Library


D3.js is an open-source library and the source code of the library is freely available on the web at
https://d3js.org/ website. Visit the D3.js website and download the latest version of D3.js (d3.zip).
After the download is complete, unzip the file and look for d3.min.js. This is the minified version
of the D3.js source code. Copy the d3.min.js file and paste it into your project's root folder or any
other folder, where you want to keep all the library files. Include the d3.min.js file in your HTML
page.

Include D3 Library from CDN


To use D3.js in your web page, add a link to the library:
<script src="http://d3js.org/d3.v3.min.js"> </script>

1|Page
D3 Features:
Uses Web Standards: D3 is an extremely powerful visualization tool to create interactive data
visualizations. It exploits the modern web standards: SVG, HTML and CSS to create data
visualization.
Data Driven: D3 is data driven. It can use static data or fetch it from the remote server in different
formats such as Arrays, Objects, CSV, JSON, XML etc. to create different types of charts.
DOM Manipulation: D3 allows you to manipulate the Document Object Model (DOM) based on
your data.
Data Driven Elements: It empowers your data to dynamically generate elements and apply styles
to the elements, be it a table, a graph or any other HTML element and/or group of elements.
Dynamic Properties: D3 gives the flexibility to provide dynamic properties to most of its
functions. Properties can be specified as functions of data. That means your data can drive your
styles and attributes.
Types of visualization: With D3, there are no standard visualization formats. But it enables you
to create anything from an HTML table to a Pie chart, from graphs and bar charts to geospatial
maps.
Custom Visualizations: Since D3 works with web standards, it gives you complete control over
your visualization features.
Transitions: D3 provides the transition() function. This is quite powerful because internally, D3
works out the logic to interpolate between your values and find the intermittent states.
Interaction and animation: D3 provides great support for animation with functions like
duration(), delay() and ease(). Animations from one state to another are fast and responsive to user
interactions.

Advantages of D3:
 D3.js is a Javascript library. So, it can be used with any JS framework of your choice like
Angular.js, React.js or Ember.js.
 D3 focuses on data, so it is the most appropriate and specialized tool for data visualizations.
 D3 is open-source. So you can work with the source code and add your own features.
 It works with web standards so you don't need any other technology or plugin other than a
browser to make use of D3.
 D3 works with web standards like HTML, CSS and SVG, there is no new learning or
debugging tool required to work on D3.
 D3 does not provide any specific feature, so it gives you complete control over your
visualization to customize it the way you want. This gives it an edge over other popular tools
like Tableau or QlikView.
 Since D3 is lightweight, and works directly with web standards, it is extremely fast and works
well with large datasets.

2|Page
Making Selection:
Selections is one of the core concepts in D3.js. It is based on CSS selectors. It allows us to select
one or more elements in a webpage. In addition, it allows us to modify, append, or remove elements
in a relation to the pre-defined dataset.
D3.js helps to select elements from the HTML page using the following two methods −
select() - Selects only one DOM element by matching the given CSS selector. If there are more
than one elements for the given CSS selector, it selects the first one only.
selectAll() - Selects all DOM elements by matching the given CSS selector.

The select() method:


The select() method selects the HTML element based on CSS Selectors. In CSS Selectors, you can
define and access HTML-elements in the following three ways −
 Tag of a HTML element (e.g. div, h1, p, span, etc.,)
 Class name of a HTML element
 ID of a HTML element

Example:
<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"> </script>
</head>
<body>
<div>
Hello World!
</div>
<div div class = "myclass">
Good Morning!
</div>
<div id = "myid">
Have a Nice Day!
</div>

<!-- To Change the text of selected element add following code. -->
<!-- <script> -->
<!-- d3.select("#myid").text("Bye!"); -->
<!-- </script> -->
</body>
</html>

3|Page
Output:

The selectAll() method:


<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"> </script>
</head>
<body>
<div>
Hello World!
</div>
<div class = "myclass">
Good Morning!
</div>
<div id = "myid">
Have a Nice Day!
</div>
<script>
d3.selectAll("div").text("Data Visualization");
</script>
</body>
</html>

Output:

4|Page
Adding DOM Elements
<!DOCTYPE html>
<html>
<head>
<script src = "https://d3js.org/d3.v4.min.js"> </script>
</head>
<body>
<div class = "myclass">
Hello World!
</div>
<script>
d3.select("div.myclass").append("span").text("from D3.js");
</script>
</body>
</html>

Modifying Elements:
D3.js provides various methods, html(), attr() and style() to modify the content and style of the
selected elements.
The html() Method: The html() method is used to set the html content of the selected / appended
elements.
<!DOCTYPE html>
<html>
<head>
<script src = "https://d3js.org/d3.v4.min.js"> </script>
</head>
<body>
<div class = "myclass">
Hello World!
</div>
<script>
d3.select(".myclass").html("Hello World! <span>from D3.js</span>");
</script>
</body>
</html>

5|Page
The attr() Method: The attr() method is used to add or update the attribute of the selected
elements.
<!DOCTYPE html>
<html>
<head>
<title> ATTR Method </title>
<script src = "https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<div class = "myclass">
Hello World!
<a> Data Visualization </a>
</div>
<script>
d3.select(".myclass").attr("style", "color: red");
d3.select("a").attr("href","https://www.w3schools.com");
</script>
</body>
</html>

The style() Method: The style() method is used to set the style property of the selected elements.
<!DOCTYPE html>
<html>
<head>
<title> STYLE Method </title>
<script src = "https://d3js.org/d3.v4.min.js"> </script>
</head>
<body>
<div class = "myclass">
Hello World!
</div>
<script>
d3.select(".myclass").style("color", "red");
</script>
</body>
</html>

6|Page
Reading CSV File:
<!DOCTYPE html>
<html>
<head>
<script src = "https://d3js.org/d3.v3.min.js"> </script>
</head>

<body>
<script>
d3.csv("http://127.0.0.1:8807/SampleCSV.csv", function(data) {
//Loading Data
for (i=0; i<data.length; i++){
document.write(data[i].Name + ": " + data[i].Age + "</br>");
}

//Filtering Data
var a = 32;
var filtData = data.filter(function(element){return element.Age == a});
document.write("</br>DATA FILTERING </br>");
for (i=0; i<filtData.length; i++) {
document.write(filtData[i].Name + ": " + filtData[i].Age + "</br>");
}
});
</script>
</body>
</html>

SampleCSV.csv
Name,Age
John,30
Jane,32
Bob,50
July,32
Alice,39
June,32

7|Page
Reading JSON File:
<!DOCTYPE html>
<html>
<head>
<script src = "https://d3js.org/d3.v3.min.js"> </script>
</head>
<body>
<script>
function filterJSON(data, key, value)
{
var result = [];
for (var i in data) {
if (data[i][key] === value) {
result.push(data[i]);
}
}
return result;
}

d3.json("http://127.0.0.1:8807/SampleJSON.json", function(data)
{
//Loading Data
document.write(data[1].region + " EMP: " + data[1].emp + ",
Amount: " + data[1].amount + "</br>");
//Display keys of JSON object
document.write("Keys: " + Object.keys(data) + "</br>");
//Filtering Data
var a = 150;
var filtData = filterJSON(data, 'emp', 150);
for (i=0; i<filtData.length; i++) {
document.write(filtData[i].region + ": " +
filtData[i].emp + "</br>");
}
});
</script>
</body>
</html>

SampleJSON.json
{ "0": {"region": "Northeast", "emp":150, "amount":"115,000"},
"1": {"region": "Southeast", "emp":150, "amount":"95,000"},
"2": {"region": "West", "emp":325, "amount":"265,000"}
}

8|Page
Reading XML File:
<!DOCTYPE html>
<html>
<head>
<script src = "https://d3js.org/d3.v3.min.js"></script>
</head>

<body>
<script>
d3.xml("http://127.0.0.1:8807/SampleXML.xml", function(d)
{
d3.selectAll("list").
data(d.documentElement.getElementsByTagName("Cat")).
enter().append("div").text(function(d) { return d.textContent; });
});
</script>
</body>
</html>

SampleXML.xml
<?xml version='1.0' ?>
<book>
<list>
<BookName> Data Visualization </BookName>
<Cat> Programming </Cat>
<Price> 2100 </Price>
</list>
<list>
<BookName> Data Visualization </BookName>
<Cat> Theory </Cat>
<Price> 1100 </Price>
</list>
<list>
<BookName> Java </BookName>
<Cat> Programming </Cat>
<Price> 5100 </Price>
</list>
</book>

9|Page
Data manipulation in d3.js
<!doctype html>
<html>
<head>
<script src="https://d3js.org/d3.v3.min.js"> </script>
</head>
<body>
<script>
//JavaScript objects are containers for named values called properties or methods.
//We can call any element of the object with its name:
var data = [
{key: "01", value: 100},
{key: "02", value: 200},
{key: "03", value: 300}
];

console.log(data);
//THE min/max of the VALUES:
document.write("Minimum is:" + d3.min(data, function(d) { return d.value; });
document.write("Maximum is:" +d3.max(data, function(d) { return d.value; }));

// AND IF YOU WANT THE min/max of the KEYS:


document.write("Minimum Key is:" + d3.min(data, function(d) { return d.key; }) );
document.write("Maximum Key is:" + d3.max(data, function(d) { return d.key; }) );

//An array is a special variable, which can hold more than one value at a time.
//Arrays use numbered indexes.
var myArray = [12, 34, 23, 12, 89];
document.write("Array is:" + myArray + "<br/>");

//Access the first element in the array.


first=myArray[0];
document.write("First Element is:" + first + "<br/>");

//Access the last element in the array.


last=myArray[myArray.length - 1];
document.write("Last Element is:" + last + "<br/>");

//Remove last element of the array. Add a new element at the end.
myArray.pop();
myArray.push(45);
document.write("New Array is:" + myArray + "<br/>");

//Index of the element '34' in the array


document.write("Index of 34 is:" + myArray.indexOf(34) + "<br/>");

//Remove elements that are provided in a second array:


var myArray = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];
10 | P a g e
var toRemove = ['B', 'C', 'G'];
filteredArray = myArray.filter( function( el ) {
return !toRemove.includes( el );
});
document.write("Filtered Array is:" + filteredArray + "<br/>");

//Keep only elements that are provided in a second array:


var myArray = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];
var toKeep = ['B', 'C', 'G', 'O', 'Z'];
filtArray = myArray.filter( function( el ) {
return toKeep.includes( el );
});
document.write("Filtered Array is:" + filtArray + "<br/>");

//Sorting
var a = [12, 34, 23, 12, 89, 54, 27];
var sorted = a.sort();
document.write("Sorted Array is:" + sorted + "<br/>");

// descending order
var desc = a.sort((a, b) => b - a);
document.write("Sorted in Reverse:" + desc + "<br/>");

//sort the employees array by name property


var employees = [
{name: 'John', salary: 90000, hireDate: "July 1, 2010"},
{name: 'David', salary: 75000, hireDate: "August 15, 2009"},
{name: 'Ana', salary: 80000, hireDate: "December 12, 2011"}
];
// sort by salary
employees.sort(function (x, y) {
return x.salary - y.salary;
});
console.table(employees);

//sort the rivers array by the length of its element


var rivers = ['Mississippi','Nile', 'Amazon', 'Congo', 'Rio-Grande'];
rivers.sort(function (a, b) {return a.length - b.length;});
console.log(rivers);
</script>
</body>
</html>

11 | P a g e
Button Click Event
<!doctype html>
<html>
<head>
<script src="https://d3js.org/d3.v6.min.js" charset="utf-8"></script>
</head>
<body>
<div>Data Visualization</div>
<div>SVG</div>
<div>HTML</div>
<div>CanvasJS</div>
<button onclick="myFun()">Click me</button>
<script >
var myFun(){
d3.selectAll("div").each(function (p, j) {
d3.select(this).text("DIVs are edited: "+j);
});
}
</script>
</body>
</html>

Mouse Hover Event


<!doctype html>
<html>
<head>
<style>
div { height: 100px; width: 100px; background-color: steelblue; margin:5px; }
</style>
<script src="https://d3js.org/d3.v6.min.js"></script>
</head>
<body>
<div> </div>
<script>
d3.selectAll("div").on("mouseover", function(){
d3.select(this).style("background-color", "orange");
}).on("mouseout", function(){
d3.select(this).style("background-color", "steelblue")
});
</script>
</body>
</html>

12 | P a g e
SVG:

<!doctype html>
<html>
<head>
<script src="https://d3js.org/d3.v6.min.js"></script>
</head>
<body>
<script>
d3.select("body").append("svg").attr("height",300).attr("weight",500);
//Line
d3.select("svg").append("line")
.attr("x1",30).attr("y1",30)
.attr("x2",100).attr("y2",100).attr("stroke","gray")
.attr("stroke-width",5);
//Rectangle
d3.select("svg").append("rect")
.attr("x",110).attr("y",110)
.attr("width",50).attr("height",50).attr("stroke","pink")
.attr("stroke-width",5);
//Circle
d3.select("svg").append("circle")
.attr("cx",105) .attr("cy",105)
.attr("r",10)
.attr("fill","pink");
//Ellipse
d3.select("svg").append("ellipse")
.attr("cx",140).attr("cy",180)
.attr("rx",100) .attr("ry",10)
.attr("fill","magenta")
.attr("opacity",0.5);
//Text
d3.select("svg").append("text")
.attr("x",110).attr("y",50)
.text("Hello World")
.attr("font-size",20)
.attr("stroke","green");
</script>
</body>
</html>

13 | P a g e
Grouping in SVG:
<!doctype html>
<html>
<head>
<script src="https://d3js.org/d3.v6.min.js"></script>
</head>
<body>
<svg height=300 width=300>
<g>
<circle cx=100 cy=100 r=20 fill="red"> </circle>
<line x1=100 y=120 x2=100 y2=200 stroke="black"> </line>
</g>
<g>
<circle cx=200 cy=200 r=50 fill="red"> </circle>
<line x1=300 y=300 x2=350 y2=300 stroke="black"> </line>
<rect x=150 y=100 width=50 height=30> </rect>
</g>
</svg>

<script>
var group1 = d3.select("body").append("svg")
.attr("height",300)
.attr("weight",500);
group1.append("line")
.attr("x1",30)
.attr("y1",30)
.attr("x2",100)
.attr("y2",100).attr("stroke","gray")
.attr("stroke-width",5);
group1.append("rect")
.attr("x",110)
.attr("y",110)
.attr("width",50)
.attr("height",50).attr("stroke","pink")
.attr("stroke-width",5);
</script>
</body>
</html>

14 | P a g e
Transformation in SVG:
<!doctype html>
<html>
<head>
<script src="https://d3js.org/d3.v6.min.js"> </script>
</head>
<body>
<svg height=600 width=600>
<g>
<circle cx=50 cy=50 r=20 fill="red"> </circle>
<line x1=50 y1=70 x2=50 y2=200 stroke="black"> </line>
</g>
<g id="g2">
<circle cx=200 cy=200 r=100 fill="green"> </circle>
<rect x=130 y=150 width=30 height=20> </rect>
<rect x=230 y=150 width=30 height=20> </rect>
</g>
</svg>
<script>
var grp1=d3.select("body").select("svg").select("g")
grp1.attr("transform","translate(300,300) scale(1.5,1.5)");
var grp1=d3.select("body").select("svg").select("#g2")
grp1.attr("transform","rotate(-20)");
</script>
</body>
</html>

Filtering in SVG:
<!doctype html>
<html>
<head>
<script src="https://d3js.org/d3.v6.min.js"></script>
</head>
<body>
<script>
var grp1 = d3.select("body").append("svg")
.attr("height",500).attr("width",600)
.append("g");
grp1.append("rect")
.attr("x",10).attr("y",10)
.attr("width",50).attr("height",50);

15 | P a g e
grp1.append("rect")
.attr("x",70).attr("y",10)
.attr("width",50).attr("height",50);

grp1.append("rect")
.attr("x",130).attr("y",10)
.attr("width",50).attr("height",50);

grp1.append("rect")
.attr("x",190).attr("y",10)
.attr("width",50).attr("height",50);

grp1.append("rect")
.attr("x",250).attr("y",10)
.attr("width",50).attr("height",50);

grp1.append("rect")
.attr("x",310).attr("y",10)
.attr("width",50).attr("height",50);

grp1.selectAll("rect")
.filter(":nth-child(even)")
.attr("fill","blue");

grp1.selectAll("rect")
.filter(":nth-child(odd)")
.attr("fill","yellow");

grp1.selectAll("rect")
.filter(":first-child")
.attr("fill","magenta");

grp1.selectAll("rect")
.filter(":last-child")
.attr("fill","magenta");
</script>
</body>
</html>

16 | P a g e

You might also like