0% found this document useful (0 votes)
63 views26 pages

Data Visualization: Introduction Getting Started With D3.JS Using SVG To Create Images 10 Lab Program

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
63 views26 pages

Data Visualization: Introduction Getting Started With D3.JS Using SVG To Create Images 10 Lab Program

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 26

DATA VISUALIZATION

● Introduction
● Getting Started With D3.JS
● Using SVG to Create Images
● 10th Lab Program
Presented by :
■ Harshita RS and
■ Shraddha Pattar
What is DATA VISUALIZATION?
Data visualization is the presentation of data in a pictorial or graphical format.
The primary goal of data visualization is to communicate information clearly and
efficiently via statistical graphics, plots and information graphics.

WHAT IS D3.JS? : Data Driven Document


D3.js is a JavaScript library used to create interactive visualizations in the
browser. The D3.js library allows us to manipulate elements of a webpage in the
context of a data set.
Getting Started With D3.JS
D3.js Library
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 −
>Include the D3.js library from your project's folder.
>Include D3.js library from CDN (Content Delivery Network).

<!DOCTYPE html>
<html lang = "en">
<head>
<script src = "https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<script> // write your d3 code here.. </script>
</body>
</html>
Web Standards
Before we can start using D3.js to create visualizations, we need to get familiar
with web standards. The following web standards are heavily used in D3.js.
● HyperText Markup Language (HTML)
● Document Object Model (DOM)
● Cascading Style Sheets (CSS)
● Scalable Vector Graphics (SVG)
● JavaScript
SVJ : Scalable Vector Graphics
● SVG is a way to render images on the webpage.
● SVG is not a direct image, but is just a way to create images using text.
● As its name suggests, it is a Scalable Vector.
● It scales itself according to the size of the browser, so resizing your browser
will not distort the image.
● All browsers support SVG except IE 8 and below. Data visualizations are
visual representations and it is convenient to use SVG to render visualizations
using the D3.js.
SVG Shapes
SVG has some predefined shape elements that can be used by developers:
•Rectangle <rect>
•Circle <circle>
•Ellipse <ellipse>
•Line <line>
•Polyline <polyline>
•Polygon <polygon>
•Path <path>
A typical SVG Example:
<!DOCTYPE html>
<html>
<body>

<h2>SVG rect Element</h2>

<svg width="300" height="130" xmlns="http://www.w3.org/2000/svg">


<rect width="200" height="100" x="10" y="10" rx="20" ry="20" fill="blue" />
Sorry, your browser does not support inline SVG.
</svg>

</body>
</html>
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.

<body> <div class = "myclass"> Hello World! </div>


<script> d3.select(".myclass").html("Hello World!
<span>from D3.js</span>");
</script>
</body>
<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript" src =
"https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<div class = "myclass"> Hello World!
</div> <script>
d3.select("div.myclass").append("span").tex
t("from D3.js");
</script>
</body>
</html>
Data Binding Methods:

D3 includes the following important methods for data binding.

Method Description
data() Joins data to the selected elements
enter() Creates a selection with placeholder references for missing
elements
exit() Removes nodes and adds them to the exit selection which
can be later removed from the DOM
datum() Injects data to the selected element without computing a
join.
data():

D3 is data driven. The data() function is used to join the specified array of data to
the selected DOM elements and return the updated selection. D3 works with
different types of data like Array, CSV, TSV, JSON, XML etc.
We can pass two types of value to the data() function, an array of values (number
or object) or a function of data.
The following example demonstrates how to join data as an array into your existing
DOM element using data() function.
Example: Join Data to Existing Element

<p>D3 Tutorials</p>
<script> var myData = ["Hello World!"];
var p = d3.select("body")
.selectAll("p")
.data(myData).text(function (d) {
return d;});
</script>
This is how it works:
d3.select("body") selects the HTML Body element.

.selectAll("p") - returns the paragraph element. Since there is only one paragraph
element, this will return a selection with one <p> element object.

.data(myData) - the data() function then binds our data array 'myData' to the selection
returned from the previous selection. Since our selection has single p element, the data()
function will bind the first value from our data array to the <p> element.

.text(function(d, i) { return d; }); - this text function adds the data as text to each of our
selection element. Each array value is passed as the first argument (d) to text function.
In this case, an existing text from paragraph element, 'D3 tutorial', will get replaced with
the first array value 'Hello World'.
enter():
The enter() method dynamically creates placeholder references corresponding to the number of data
values.
The output of enter() can be fed to append() method and append() will create DOM elements for which
there are no corresponding DOM elements on the page.
In the following example, there are 6 data values in our array. So enter() will create six reference
placeholders and append will create six span elements.
Example: enter() Method
<body>
<script>
var data = [4, 1, 6, 2, 8, 9];
var body = d3.select("body")
.selectAll("span")
.data(data)
.enter()
.append("span")
.text(function(d) {
return d + " "; });
</script>
</body>
d3.select("body")
This statement selects the HTML Body.

.selectAll("span")
At this point, there are no span elements in the body. So this will return an empty array.

.data(data)
We provide our data array to the data() function. Since our array has six elements, the code after
this will run six times for every element in the array.

.enter()
The enter() function checks for <span> elements corresponding to our five array elements. Since it
does not find any, it will create a span for each of the five elements.

.append("span")
And this will append above created spans to the body element.

.text(function(d) { return d + " "; });


And finally our text function adds each of the numbers from the data array as text to each of our
span selections and prints them onto the screen!
exit()
While enter() is used to add new reference nodes, exit is used to remove a node.
In the below code, all p elements will be removed. With exit(), the elements enter an exit phase. This
means that all the exited elements are stored in some invisible place ready to be removed when the
command is given. And that command is remove(). remove() will remove all the 'exited' nodes from the
DOM.
Example: exit() Method
<body>
<p>D3 Tutorials</p>
<p></p>
<p></p> <script>
var myData = ["Hello World!"];
var p = d3.select("body")
.selectAll("p")
.data(myData)
.text(function (d, i) {
return d; })
.exit()
.remove();
</script>
</body>
In the above example, HTML included three <p> elements whereas data array includes only one data
value. So, the .exit().remove() removed additional <p> elements.
datum():
The datum() function is used for static visualization which does not need updates. It binds
data directly to an element.

Example: datum() Method


<body>
<p>D3 Tutorials</p>
<script>

d3.select("body")
.select("p")
.datum(100)
.text(function (d, i) {
return d;
});
</script>
</body
D3 Method Chaining:
D3 uses a convention called method chaining. Basically what it means is that when we call a method on an object, it performs the method and returns an object. Since the method on an object returns an object, another method can be called without having to explicitly reference an object again.
D3 uses a similar technique where methods are chained together using a period.

d3.select("body").append("p").text("Hello World!");

The output of the first method is passed as an input to the next method in the chain.
Think of it as a filtered channel. The first method filters out content and provides a reference
to the filtered content to the next method, the next method further filters and passes on the
reference to the next method and so on.

Now, we could have written our D3 code without using chaining as below.

var bodyElement = d3.select("body");

var paragraph = bodyElement.append("p");

paragraph.text("Hello World!");

But the method chaining is a shorter and cleaner way of achieving this.

d3.select("body").append("p").text("Hello World!");
d3.select("body")

From the DOM, D3 selects the body element and returns a reference of the selection to the next method
in the chain which is append().

append("p")

From the filtered content that it received, the append() method works only on the reference element(s) it
received. In this case, it is the body element. Now, it creates and appends a new <p> element to the
element that it received and returns this new element to the next method in the chain.

text("Hello World!")

The text() method receives the paragraph element from the previous method and adds the text provided
to it.
Function of Data:
There are different DOM manipulation methods in D3 such as append(), style(), text() etc. Each of these functions can take in a constant value or a function as a parameter. This function is a function of data. So each of these methods will be called for each of our data values bound to the DOM. Consider the following text() function.

.text(function(d) {
return d;
});
Within this function, we can apply any logic to manipulate the data. These are anonymous functions, meaning that there is no name associated with the function.
Other than the data (or d) parameter, there are two other parameters available.

.text(function (d, i) {
console.log(d); // the data element
console.log(i); // the index element
console.log(this); // the current DOM object

return d;
});

consider the below example:


<!doctype html>
<html>
<head>
<script src="https://d3js.org/d3.v4.min.js">
</script>
</head>
<body>
<p></p>
<p></p>
<p></p>
<script>
var data = [100, 200, 300];
var paragraph = d3.select("body") .selectAll("p")
.data(data) .text(function (d, i)
{ console.log("d: " + d);
console.log("i: " + i);
console.log("this: " + this); return d; });
</script>
</body>
</html>
In the above example, the parameter "d" gives you your data element, "i" gives you the index of data in the array and this is a reference of the current DOM element. In this case, it is the paragraph element.

Notice that we have called .data(data) function above. The data() function provides data to the selected elements, in our case it is data array.
Events in D3
As in all other libraries, D3 also supports built-in events and custom events. We can bind an event listener to any DOM element using d3.selection.on() method.

Syntax:
d3.selection.on(type[, listener[, capture]]);
The on() method adds an event listener to all selected DOM elements. The first parameter is an event type as string such as "click", "mouseover" etc. The second parameter is a callback function which will be executed when an event occurs and the third optional parameter capture flag may be specified, which corresponds to the W3C useCapture flag.
The following table lists important event handling method and objects.

Event Methods Description


selection.on() Add or remove event listeners to capture event types
like click, mouseover, mouseout etc.
selection.dispatch() Captures event types like click, mouseover, mouseout.
Typenames is the eventname, listener is the event
listener
d3.event Event object to access standard event fields such as
timestamp or methods like preventDefault
d3.mouse(container) Gets the x and y coordinates of the current mouse
position in the specified DOM element.
d3.touch() Gets the touch coordinates to a container
THANK YOU
HAVE A NICE DAY!

You might also like