Data Visualization: Introduction Getting Started With D3.JS Using SVG To Create Images 10 Lab Program
Data Visualization: Introduction Getting Started With D3.JS Using SVG To Create Images 10 Lab Program
● 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.
<!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>
</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.
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.
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.
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;
});
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.