You are on page 1of 40

16MDS83 - DATA VISUALIZATION

1
16MDS83 - DATA VISUALIZATION

UNIT 4
INTRODUCTION TO D3
Technology Fundamentals:
Embedding with HTML, DOM, CSS, JavaScript,
SVG-Drawing with data-Scales
D3
1. Setting up D3
2. Adding DOM and SVG elements
3. Binding data to DOM elements
4. Using data bound to DOM elements
5. Creating SVG elements based on data
6. Using SVG co-ordinate space
7. SVG basic shapes and D3
8. D3 Scales
9. D3 text element
10. D3 Axes
D3 - Data-Driven Documents
• D3—also referred to as d3.js—is a JavaScript library for creating data visualizations
• Data-Driven Documents. The data is provided by you, and the documents are web-based
documents, meaning anything that can be rendered by a web browser, such as HTML and
SVG.
• D3 does the driving, in the sense that it connects the data to the documents.
• Fundamentally, D3 is an elegant piece of software that facilitates generation and
manipulation of web documents with data.
• Loading data into the browser’s memory
• Binding data to elements within the document, creating new elements as needed
• Transforming those elements by interpreting each element’s bound datum and setting its
visual properties accordingly
• Transitioning elements between states in response to user input
JavaScript – An Introduction
• JavaScript was initially created to “make web pages alive”.
• The programs in this language are called scripts. They can be written
right in a web page’s HTML and run automatically as the page loads.
• Scripts are provided and executed as plain text. They don’t need
special preparation or compilation to run.
• In this aspect, JavaScript is very different from another language
called Java.
JavaScript – An Introduction
• When JavaScript was created, it initially had another name: “LiveScript”. But
Java was very popular at that time, so it was decided that positioning a
new language as a “younger brother” of Java would help.
• But as it evolved, JavaScript became a fully independent language with its own
specification called ECMAScript, and now it has no relation to Java at all.
• Today, JavaScript can execute not only in the browser, but also on the server,
or actually on any device that has a special program called the JavaScript
engine.
• The browser has an embedded engine sometimes called a “JavaScript virtual
machine”.
Why JavaScript?
• JavaScript provides
• Full integration with HTML/CSS.
• Simple things are done simply.
• Support by all major browsers and enabled by default.
• The only browser technology that combines these three things.
• it’s the most widespread tool for creating browser interfaces.
• JavaScript also allows to create servers, mobile applications, etc.
• A library is a JavaScript file that contains a bunch of functions, and
those functions accomplish some useful task for your webpage.
JavaScript Framework
• At their most basic, JS frameworks are collections of JavaScript code
libraries that provide developers with pre-written JS code to use
for routine programming features and tasks
• JS frameworks doesn’t just offer an individual solution to a coding
problem, it provides a structure like a skeleton or a scaffolding that
organizes the parts of your site where the framework is implemented.
• While some frameworks are designed to live underneath all of your
site or web app’s code, other frameworks—like the increasingly
popular Vue—allow for incremental use.
How D3.js
works
• Fundamentally, D3 is an elegant piece of software that facilitates
generation and manipulation of web documents with data.
• It does this by:
• Loading data into the browser’s memory
• Binding data to elements within the document, creating new elements as
needed
• Transforming those elements by interpreting each element’s bound datum
and set‐ ting its visual properties accordingly
• Transitioning elements between states in response to user input
• The transformation step is most important, as this is where the
mapping happens. D3 provides a structure for applying these
transformations but the user defines the mapping rules
What D3.js Doesn’t Do
• D3 doesn’t generate predefined or “canned” visualizations for you.
This is on pur‐ pose. D3 is intended primarily for explanatory
visualization work, as opposed to exploratory visualizations.
• • D3’s core functionality doesn’t handle bitmap map tiles, such as
those provided by Google Maps or Cloudmade. D3 is great with
anything vector—SVG images or GeoJSON data—but wasn’t
originally intended to work with traditional map tiles
• D3 doesn’t hide your original data. Because D3 code is executed on
the client side (meaning, in the user’s web browser, as opposed to on
the web server), the data you want visualized must be sent to the
client. If your data can’t be shared, then don’t use D3.
HTTP
• HTTP stands for Hypertext Transfer Protocol, and it’s the most
common protocol for transferring web content from server to client.
• The “S” on the end of HTTPS stands for Secure.
• HTTPS connections are used whenever information should be
encrypted in transit, such as for online banking or e-
commerce
• “Marking up” is the process of adding tags to create elements. HTML
tags begin with < and end with >, as in , which is the tag indicating a
paragraph of text. Tags usually occur in pairs, in which case adding
an opening and closing pair of tags creates a new element in the
document structure. Closing tags are indicated with a slash that
closes or ends the element, as in
<p>This is a really interesting paragraph</p>
• Cascading Style Sheets are used to style the visual presentation of
DOM elements. A simple CSS stylesheet looks like the following:
JavaScrip
t•
we write JavaScript code (or, a “script”) in a text file, and then load
that file to the browser in a web page
• Variables
• Variables are containers for data. A simple variable holds one value:
• Arrays
• An array is a sequence of values, conveniently stored in a single variable.
Keeping track of related values in separate variables is inefficient:
• Objects
• Arrays are great for simple lists of values, but with more complex datasets,
need to put your data into an object. We use curly brackets {} to
indicate an object. In between the brackets, we include properties and
values. A colon : separates each property and its value, and a comma
separates each property/value pair:
Adding DOM Element
• D3 looks at the document and selects the first descendant DOM
element that contains the tag body. Once an element is selected,
D3. js allows you to apply operators to the element you have
selected. These operators can get or set things like "attributes",
"properties", "styles", "HTML", and "text content".
Drawing Data()
index.html
We can start by defining a simple web page,
which has a header (h1) and an svg element that
CSS Style
will hold our visualization. In the style tags, we
can add C S S styling for both elements defined in
the HTML.

HTML
Adding Elements
Manually specifying elements
We can manually add elements to the DOM, and
specify properties such as the x and y position,
and the title (which appears as a tooltip on
hover).

Elements can be added directly to the


<svg></svg> element, or to <g></g> svg groups.
They will inherit the properties of their parent
group (like location and orientation).
Positioning Elements
Keep in mind that the origin for positioning
elements is the upper left corner. (0,0)

(60,25)

(120,465)
Selections
Selecting elements
d3.select() and d3.selectAll() can be used to
access DOM elements by name, class, id, or
many other css selectors. d3.select() selects only
the first element that matches the css selectors
while d3.selectAll() selects all matched
elements.
Modifying selected elements
You can use access and modify the properties of
selections with attr(), text(), style(), and other
operators. Most D3 selection methods return the
selection, allowing us to chain the operator calls.
Appending elements
Through append(), we can add new elements
anywhere in the DOM. We can then use
operators or C S S to set the properties of the
element.

We can also get rid of elements with remove().

Finally, we can store selections in variables for


future use.

D3 selections page extremely helpful!


Data Binding
Binding
We can use the data() function to bind data to a We can also use data() or datum() to access the
selection. data that belong to a selection.
selectAll().data().enter().append()
1. Select all of our circles (currently we don’t
have any).
2. Bind our data (in this case, 5 rows worth)
3. Enter each new datum from our selection.
4. Append a new DOM element. There are
now 5 new elements, each with their own
unique data.
5. Append titles to the new elements.
6. Merge our new elements into our original
selections.
7. Set attributes with operators, using
anonymous functions.
selectAll().data().enter().append()
1
1. Select all of our circles (currently we don’t 2
3 4
have any).
2. Bind our data (in this case, 5 rows worth)
3. Enter each new datum from our selection.
4. Append a new DOM element. There are 5

now 5 new elements, each with their own 6

unique data. 7

5. Append titles to the new elements.


6. Merge our new elements into our original
selections.
7. Set attributes with operators, using
anonymous functions.
Scales
Scales
• “Scales are functions that map from an input domain to an output
range.”
• The values in any dataset are unlikely to correspond exactly to pixel
measurements for use in your visualization. Scales provide a
convenient way to map those data values to new values useful for
visualization purposes.
Scales : Domains and Ranges
• A scale’s input domain is the range of
possible input data values.
• A scale’s output range is the range of
possible output values, commonly used as
display values in pixel units. The output
range is completely up to you, as the
information designer.
• For example, create a scale with an input
domain of [100,500] and an output range
of [10,350]. If you handed the low input
value of 100 to that scale, it would return
its lowest range value, 10. If you gave it
500, it would spit back 350. If you gave it
300, it would hand 180 back to you on a
silver platter. (300 is in the center of the
domain, and 180 is in the center of the
range.)
Scales : Normalization
• Normalization is the process of mapping a numeric value to a new
value between 0 and 1, based on the possible minimum and
maximum values. For example, with 365 days in the year, day number
310 maps to about 0.85, or 85 percent of the way through the year
Scales : Creating a Scale
var scale = d3.scale.linear();
scale.domain([100, 500]);
scale.range([10, 350]);
OR
var scale =
d3.scale.linear() .dom
ain([100,
500]) .range([10,
350]);
Scales : Scaling a Scatter Plot
• Instead of specifying fixed values for the domain, we can use the
convenient array functions d3.min() and d3.max() to analyze our
data set on the fly
var dataset = [ [5, 20], [480, 90], [250, 50], [100, 33], [330, 95], [410, 12], [475, 44], [25, 67],
[85,
21], [220, 88] ];
• d3.max(dataset); // Returns [85, 21]. What???

d3.max(dataset, function(d) { return d[0]; }); // function(d) is an accessor function


function(d) {
return d[0]; //Return the first value in each subarray
}
Scales : Setting Up Dynamic Scales
• Scales function for x-axis
var xScale = d3.scale.linear() .domain([0, d3.max(dataset, function(d) { return d[0]; })])
.range([0, w]);
• Scales function for y-axis
var yScale = d3.scale.linear() .domain([0, d3.max(dataset, function(d) { return d[1]; })])
.range([0, h]);
• the domain and range are specified as two-value arrays in hard brackets.
• low end of the input domain to 0. The upper end of the domain is set to the
maximum value in dataset
• output range is set to 0 and w, the SVG’s width.
Scales : Incorporating Scaled Values
Scales : Other methods
d3.scale.linear() has several other handy methods that deserve a brief
mention here:
• nice() : This tells the scale to take whatever input domain that
you gave to range() and expand both ends to the nearest
round value
• rangeRound() : Use rangeRound() in place of range(), and all
values output by the scale will be rounded to the
nearest whole number. This is useful if you want shapes to have
exact pixel values, to avoid the fuzzy edges that could arise
with antialiasing.
• clamp() : By default, a linear scale can return values outside of the
specified range. Calling clamp(true) on a scale, however, forces
all output values to be within the specified range.
Scales : Other Scales
• sqrt : A square root scale.
• pow : A power scale
• log : A logarithmic scale.
• Quantize : A linear scale with discrete values for its output range, for
when you want to sort data into “buckets.”
• Ordinal : Ordinal scales use nonquantitative values
• d3.time.scale() : A scale method for date and time values, with special
handling of ticks for dates.

You might also like