You are on page 1of 57

Introduction to D3.

js
● D3 is Data Driven Documents
● D3.js is a JavaScript library for manipulating documents based on data.
● D3 helps you bring data to life using HTML, SVG, and CSS.
● D3’s emphasis on web standards gives you the full capabilities of modern
browsers without tying yourself to a proprietary framework, combining
powerful visualization components and a data-driven approach to DOM
manipulation.
● 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.
1
Introduction to D3.js
● 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.

2
Getting setup with D3
● Download D3.js from
https://github.com/d3/d3/releases/download/v6.6.2/d3.zip
● Put the js file in the same directory, where you are creating your other files and
use <script src="d3.v6.min.js"></script>
● OR
● Use the d3.js from d3js.org. Use the following in your html file
● <script src="https://d3js.org/d3.v6.min.js"></script>-- is
preferred

3
Features Of D3.js
● Data-Driven: It is mainly used to explore and analyze data and create interactive
real-time graphs, charts, and extensive ways to visualize the data.
● DOM Manipulation: This is an open-source JavaScript library that converts data
in various visualization formats by manipulating DOM elements.
● Utilizes Web Standards: It uses Document Object Model (DOM), HTML,
Cascading Style sheets (CSS), Scalable Vector Graphics (SVG), and canvas to
create data visualization formats.
● Fast and Interactive: It is highly responsive to change in data, and can quickly
animate or transform selected DOM element from one state to another state.
● Display Dynamic Transitions: This library is designed to create a fast dynamic
transition to generate quick responsive visualization with DOM.
4
Benefits Of Using D3.js
● It is an open-source JavaScript library that can be used along with other
JavaScript frameworks such as Angular.JS, Ember.JS, or React.
● This library is open-source, so one can add their own features to the source code
to accomplish their goals.
● It handles web standards like DOM, HTML, CSS, SVG, and canvas, hence it does
not need any other plug-in other than a browser, it does not need any additional
debugging or learning tool.
● It can create dynamic, real-time transformation by manipulating DOM elements,
quickly into data visualization without any latency.
● It works on data and is specialized and appropriate with data visualization
functions contained in the JavaScript library.
5
Making selections-using DOM
● Modifying documents using the W3C DOM API is tedious: the method names are
verbose, and the imperative approach requires manual iteration and
bookkeeping of temporary state. For example, to change the text color of
paragraph elements:

var paragraphs = document.getElementsByTagName("p");

for (var i = 0; i < paragraphs.length; i++) {

var paragraph = paragraphs.item(i);

paragraph.style.setProperty("color", "blue", null);

} 6
Making selections
● 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. If you are familiar with
selecting elements with jQuery, D3.js selectors are almost the same.

7
Making selections
● D3 employs a declarative approach, operating on arbitrary sets of nodes called
selections. For example, you can rewrite the above loop as:
● d3.selectAll("p").style("color", "blue");
● Yet, you can still manipulate individual nodes as needed:
● d3.select("body").style("background-color", "black");
● Selectors are defined by the W3C Selectors API and supported natively by
modern browsers.
● The above examples select nodes by tag name ("p" and "body", respectively).
Elements may be selected using a variety of predicates, including containment,
attribute values, class and ID.

8
Making selections
● 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 suffice for the vast majority of needs. Direct access to the underlying DOM
is also possible, as each D3 selection is simply an array of nodes.

9
Changing selection’s attribute
● All <p> tags attribute value change
● d3.selectAll("p").style("color", "red");
● Changing individual attribute value
● d3.select("body").style("background-color", "white");

10
Changing selection’s attribute
● All pags attribute value change
● d3.selectAll("p").style("color", "white");
● Changing individual attribute value
● d3.select("body").style("background-color", "#0000ff");

11
Changing selection’s attribute
● All pags attribute value change
● //Hue-Saturation-Lightness (HSL) is an alternative to the
RGB color model

d3.selectAll("p").style("color", function() {

return "hsl(" + Math.random() * 360 + ",100%,50%)";

});

Refresh the page as many times, you will see different color of CKPCET.
12
Changing selection’s attribute

● To alternate shades of gray for even and odd nodes:

d3.selectAll("p").style("color", function(d, i) {

return i % 2 ? "#fff" : "#eee";});

13
Selection by Class name
<div class=”myclass”>

Hello world!

</div>

alert(d3.select(".myclass").text());

14
Selection by ID
● Every element in a HTML page should have a unique ID. We can use this unique
ID of an element to access it using the select() method as specified below.

<div id = "hello">

Hello World by ID!

</div>

d3.select(“#<id of an element>”)

alert(d3.select("#hello").text());

15
Modifying Elements
● D3.js provides various methods, html(), attr() and style() to modify the content
and style of the selected elements.
● The html() Method: is used to set the html content of the selected / appended
elements.

<body><div class = "myclass">


Hello World!
</div>

<script>
d3.select(".myclass").html("Hi students! <span>from
D3.js</span>");
</script></body>
O/p: Hello World! from D3.js 16
Modifying Elements:attr() Method
● The attr() method is used to add or update the attribute of the selected elements.
<body>
<div class = "myclass">
Hello World!
</div>

<script>
d3.select(".myclass").attr("style", "color: red");
</script>

O/P:
17
Modifying Elements:style() method
● The style() method is used to set the style property of the selected elements.

<script>
d3.select(".myclass").style("color", "red");
</script>

O/P:

18
Prerequisites To Learn D3.js
● Text editor: A text editor such as Notepad++ or Vim is needed to write
programming code like HTML, CSS, JavaScript, and integrate them to produce the
desired requirement.
● Web browser: Any one of the modern web browsers, such as Firefox, Google
Chrome, Safari, Opera, or IE9 should be installed to check and verify the output
that is produced after integrating the code.
● HTML: Good understanding of HTML tags and structure will help to build a basic
web page and align elements to bring visualization to the next level.
● CSS: Cascading Style Sheet (CSS) is used to apply styles including design, layout,
and screen size to web pages.

19
Prerequisites To Learn D3.js
● DOM: Strong understanding of Document Object Model (DOM) is essential as it
will be easier to know the structure and content of web documents, access DOM
elements for D3.js for data visualization.
● JavaScript: Familiarity of fundamentals and JavaScript Objects is a prerequisite
for learning and implementing D3.js into our application so that data
visualization can be viewed in the webserver.
● Web Server: It is essential to have a web server installed like Apache Tomcat or
IIS (Internet Information Services) server, so that data can be uploaded
externally in an array, object, XML, CSV, JSON formats and can be transformed
with the help of D3.js into visualization formats such as graphs, charts, and
geospatial visualization.
20
Loading and filtering External data : Building a graphic
that uses all of the population distribution data, Data
formats you can use with D3

21
Loading external data
● D3 can handle different types of data defined either locally in variables or from
external files.
● D3 methods to load different types of data from external files.
Method Description

d3.csv() Sends http request to the specified url to load .csv file or
data and executes callback function with parsed csv data
objects.

d3.json() Sends http request to the specified url to load .json file or
data and executes callback function with parsed json data
objects.

22
Loading external data
● D3 can handle different types of data defined either locally in variables or from
external files.
● D3 methods to load different types of data from external files.
Method Description

d3.tsv() Sends http request to the specified url to load a .tsv file or
data and executes callback function with parsed tsv data
objects.

d3.xml() Sends http request to the specified url to load an .xml file or
data and executes callback function with parsed xml data
objects.

23
Loading external data
● D3 can handle different types of data defined either locally in variables or from
external files.
● D3 methods to load different types of data from external files.
Method Description

d3.html() Sends http request to the specified url to load .html file or
data and executes callback function with parsed html data
objects.

d3.text() Sends http request to the specified url to load .text file or
data and executes callback function with parsed text data
objects.

24
Load csv file
● Method: d3.csv(url[, row, callback]);
● person.csv file

Name,Age
Ami,16
Chiku,12
Baku,10

25
Load csv file
<!DOCTYPE html>
<html>
<head>
<title>Load CSV data</title>
<script type="text/javascript"
src="d3.v6.min.js"></script>
</head>
<body>
<script type="text/javascript">
d3.csv("person.csv", function(data) {
console.log(data)
})
</script>
</body>
</html>
26
Load csv file : Output
● Chrome browser-
>Three vertical
dots->More Tools->
Developer Tools

27
Load csv file : Output
● Click on Console
● Messages ->
Object

28
Load csv file

29
CSV Data

30
Load XML data: employee.xml file
<?xml version="1.0" encoding="UTF-8"?>
<root>
<row>
<Name>John</Name>
<Age>30</Age>
</row>
<row>
<Name>Jane</Name>
<Age>32</Age>
</row>
</root>

31
Load XML data
<!DOCTYPE html>
<html>
<head>
<title>Load XML data</title>
<script type="text/javascript"
src="https://d3js.org/d3.v6.min.js"></script>
</head>
<body>
<script type="text/javascript">
d3.xml("employee.xml", function(data) {
console.log(data);

});
</script></body></html>
32
Load XML data:Output

33
Load Json Data : json file:users.json
[{
"name": "Ami",
"age": 10,
"location": "India"
},
{
"name": "Eva",
"age": 12,
"location": "USA"
},

34
Load Json Data : json file
{
"name": "Sup",
"age": 42,
"location": "Singapore"
},
{
"name": "Viks",
"age": 40,
"location": "Germany"
}]

35
Load json data and print on web page
● The d3.json() method returned a formatted data object. It also returned an argument
"error"
● d3.json("/data/users.json", function(error, data) {
● The output we want to put on our page in body tag
● d3.select("body")
● We choose output data in <p> tag.
● .selectAll("p")
● We bind the data and pass to next line of code
● .data(data)
● enter() Function receives the values from data function, but we haven’t referenced the <p>
tag, it returns empty placeholder references to the new elements.
● .enter()

36
Load json data and print on web page
● We now have the references to our elements. The append() method adds these elements to
the DOM.
● .append("p")
● Most d3 functions accept functions as parameters. we have passed an anonymous function
to the text method that returns a concatenation of name and location from our data object.
text() is called and bound to each of our page elements with the corresponding data value.
● .text(function(d) { return d.name + ", " + d.location; });
● If we want to handle error, we can write,
● if (error) {
● return console.warn(error);
● }

37
D3 code to load and print json Data
<script type="text/javascript">
d3.json("users.json", function(error, data) {
console.log()
d3.select("body")
.selectAll("p")
.data(data)
.enter()
.append("p")
.text(function(d) {
return d.name + "::: " + d.location;
});
});
</script>
38
JSON data output

39
Load Text Data: text file
Ami
Ash
Hetu
Betu

40
Load Text Data
<head>

<script src=
"https://d3js.org/d3.v6.min.js">
</script>
</head>
<body>
<script>
d3.text("users.txt", function (d) {
console.log(d);
});
</script>
</body>
41
Load Text Data: Output

42
Filtering the data
● D3.js selection.filter() Function is used to filter the data
● The d3.selection.filter() function in d3.js is used to filter the given selection and
return a new selection for which the filter is true. The filter to be used may be a
string or a function.
● Syntax:
● selection.filter(filter);
● Parameters: This function accepts one parameter as mentioned above and
described below:
○ filter: It is a string or a function that would be used to filter a selection. The filter is applied to
each selected element when using a function.
○ Return Values: This function returns the new selection.

43
Filtering the data
<!DOCTYPE html>
<html lang="en">

<head>
<script src=
"https://d3js.org/d3.v6.min.js">
</script>
<script src=
"https://d3js.org/d3-selection.v1.min.js">
</script>
</head>

44
Filtering the data: odd rows
<body> <div>
<b>1. This text is in bold</b>
<b>2. This text is also in bold</b>
<b>3. CKPCET</b>
<b>4. Computer Engineering</b>
<b>5. Data visualization</b>
</div><script>
let selection = d3.selectAll("b")
.filter(":nth-child(odd)")
//even-.filter(":nth-child(even)")
.nodes();
selection.forEach((e) => {
console.log(e.textContent)})
</script></body></html>
45
Filtering the data:Output

46
Creating a server to upload your data
● Typically with Apache or any other web server, data directory is made.
● In that the data, i.e. xml, csv, json, text files are put. We here put in same
directory as our scripts are there.
● If we put in the data directory of htdocs folder of apache web server, we can
access it as http://localhost/data/x.csv or /data/x.csv

47
Next Lecture

48
D3’s function for loading data
● D3’s functions for Loading the data we have seen in for text, csv, tsv, xml, json,
html files. Let’s see code for html files.
● <head><script type="text/javascript"
src="https://d3js.org/d3.v6.min.js"></script></head>

<body>
<script type="text/javascript">
d3.html("person.html", function(data) {
console.log(data)
});
</script>

49
D3’s function for loading html data :output

50
Dealing with Asynchronous requests
<script>
Var popdata;
d3.csv("person.csv", function (d) {
popdata=d;
});
console.log(popdata);
</script>
● If above script is there, result would be unexpected. E.g.undefined.
● It seems like popData should be the old, familiar array, when console.log(data)
was part of the callback function. But there’s a very good reason why it isn’t.
● When you use d3.csv(), your script doesn’t wait for the callback function to
finish before it starts running the rest of the code. In technical terms, D3 makes
external requests asynchronously 51
Dealing with Asynchronous requests
<script>
var popdata;
d3.csv("person.csv", function (d) {
popdata=d;
});
console.log(popdata);
</script>
● So for large data set—one that takes multiple seconds to load. You don’t really
want all of your code to be held up by that load time.
● Ideally, everything that doesn’t involve your data will run while your data is
being pulled in so that all of the non-data-driven stuff on your page can initialize.

52
Dealing with Asynchronous requests
● Practically speaking, what this means is that everything you do with external
data has to happen inside the callback function. So, if you wanted to change the
code above so it actually works, you would need to do this:

<script>
var popdata;
d3.csv("person.csv", function (d) {
popdata=d;
console.log(popdata);
});
</script>

53
Loading Large Data Sets
<script>
data = d3.csv("alldata.csv", function(d) {
console.log(d);
});
</script>

54
Loading Large Data Sets:Output

55
Load and format large dataset
<head><title>Large Data set load and format</title>
<script src="https://d3js.org/d3.v6.min.js"></script>
</head>
<body>
<script type="text/javascript">
d3.csv("cities.csv").then(function(data) {
data.forEach(function(d) {
//format output as city: value,population: value,...
d.population = +d.population;
d["land area"] = +d["land area"];
});
//printing first line only
console.log(data[0]);
});</script>
56
Load and format large dataset

57

You might also like