KEMBAR78
D3JS | PDF | Document Object Model | Html
0% found this document useful (0 votes)
26 views31 pages

D3JS

D3.js is a JavaScript library designed for creating data-driven documents, utilizing web standards like HTML, CSS, and SVG for visualization. It simplifies DOM manipulation and allows for the creation of dynamic, interactive web graphics through a data-driven approach. The document provides an overview of D3.js functionalities, including how to create charts, manage data, and utilize SVG elements effectively.

Uploaded by

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

D3JS

D3.js is a JavaScript library designed for creating data-driven documents, utilizing web standards like HTML, CSS, and SVG for visualization. It simplifies DOM manipulation and allows for the creation of dynamic, interactive web graphics through a data-driven approach. The document provides an overview of D3.js functionalities, including how to create charts, manage data, and utilize SVG elements effectively.

Uploaded by

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

Vis ualisation de

données mas s ives


Data Driven Documents (D3.js)

Timothy Bell
I3s - Université Côte d'Azur

timothy.bell@i3s.unice.fr
What is d3.js?
● A JavaScript library for creating documents that contain data.
● Made for web, manipulates CSS, HTML, SVG.
● Any modern browser, (personal computer, television, phone, etc. )
● It combines powerful visualization components and a data-driven approach to DOM
manipulation.

2
Overview of Web Standards

● HTML (HyperText Markup Language)


● CSS (Cascading Stylesheets)
● DOM (Document Object Model)
● SVG (Scalable Vector Graphics)

● ES6 (ECMAScript 6)

● Bundle.js

3
HTML (HyperText Markup Language)

● HTML use a set of tags to define the different structural


components of a webpage:
○ <h1>, <h2>, …, <h6> tags define headers
○ <p> tags define paragraphs
○ <ol> and <ul> are ordered and unordered lists
● Browsers have common ways to display these tags:
○ lists show up like lists, and headers like headers.
● The <div> and <span> tags are special:
○ browsers do not apply default styles to them, so that they can be used to index.html
define custom groups. <!DOCTYPE html>
<html>
<head>
<title>TITLE GOES HERE</title>
</head>
<body>
<p> MAIN CONTENT GOES HERE</p>
</body>
</html>

4
CSS (Cascading Stylesheets)
● CSS is a language for styling HTML pages.
● CSS styles (also known as selectors) are typically applied to HTML tags based on their name, class,
or identifier.

CSS HTML Result (HTML + CSS)


/* Applied to all <p> tags */ <!DOCTYPE html>
p { <html>
color:blue; <head>
} <title>TITLE GOES HERE</title>
</head>
/* Applied to all tags with the class “red” */ <body>
.red { <div>
background: red; <p> Normal Paragraph</p>
} <p class=”red”>Red
Paragraph</p>
/* Applied to the tag with the id “some-id” */ </div>
#some-id {
font-style: italic; <ol>
} <li id=”some-id”>Unique
element</li>
/* Applied only to <p> tags inside <li> tags */ <li>Another list element</li>
li p { <li>
color: #0C0; <p>Paragraph inside list
} element</p>
<p>Second paragraph</p>
</li>
</ol>
</body>
</html>
5
DOM (Document Object Model)
● When a web page is loaded, the browser creates a Document Object Model of the page.
● The HTML DOM is a standard object model and a programming interface for HTML. It defines:
○ HTML elements as objects
○ The properties of all HTML elements
○ The methods to access all HTML elements
○ The events for all HTML elements
● In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML
elements.

parent node

child nodes
sibling node

6
JavaScript HTML DOM
● JavaScript is the programming language of HTML and the Web.
● DOM and JavaScript allow the creation of dynamic HTML:
○ changing/adding/removing HTML elements and its attributes;
○ changing the CSS style of elements and attributes;
○ react to existing HTML events in the page;
○ creating new events.

<!DOCTYPE html>
<html>
<head>
<title>TITLE GOES HERE</title>
</head>
<body>

<h1>My First JavaScript</h1>

<button type="button" onclick="document.getElementById('demo').innerHTML = Date()">


Click me to display Date and Time.
</button>

<p id="demo"></p>

</body>
</html>
7
DOM + JavaScript D3 API
The standard DOM API is somewhat verbose, therefore libraries such as D3 provide syntactic sugar to ease
the manipulation of HTML elements, styles and attributes.

HTML DOM API (JavaScript)


document.getElementById("some-id")
<!DOCTYPE html> // <li id=”some-id”>Unique element</li>
<html>
<head> document.getElementsByTagName("p").length;
<script type="text/javascript" // 4
src="https://d3js.org/d3.v5.min.js"></script>
<title>TITLE GOES HERE</title> var reds = document.getElementsByClassName("red")
</head> // [<p class=”red”>Red Paragraph</p>]
<body>
<div> reds[0].innerText
<p> Normal Paragraph</p> // “Red Paragraph”
<p class=”red”>Red Paragraph</p>
</div>

<ol>
D3.js
<li id=”some-id”>Unique element</li>
<li>Another list element</li> d3.select("#some-id")
<li> // [Array(1)]
<p>Paragraph inside list element</p>
<p>Second paragraph</p> d3.selectAll("p").size();
</li> // 4
</ol>
</body> var reds = d3.selectAll(".red")
</html> // [Array(1)]

reds.text()
// “Red Paragraph”
8
DOM + JavaScript D3 API
● The DOM also handles tracking elements as they are rendered, e.g. mouse movement.
○ Listeners may be attached to these events to add various levels of interactivity to the web page, e.g. mouseover, mouseleave

● D3 has some nice helpers for working with events as well.


○ Note: We can chain d3 methods, usually starting with a selection (i.e. they return themselves, so we can group them visually).

DOM API (JavaScript)

HTML var clickMe = document.getElementById(“click-me”);

<!DOCTYPE html> clickMe.onclick = function() {


<html> if (this.style.backgroundColor) {
<head> this.style.backgroundColor = “ ”;
<title>TITLE GOES HERE</title> } else {
</head> this.style.backgroundColor = “red”;
<body> }
<h1 id=”click-me”> }
Click on me!
</h1>
<p class=”hover-me”>
Hover over me!
</p> D3.js
<p class=”hover-me”>
OK now hover over here!
</p> d3.selectAll(".hover-me")
<p class=”hover-me”> .on(“mouseover”, function() {
Hover here too! this.style.backgroundColor = “yellow”;
</p> })
.on(“mouseout”, function() {
</body> this.style.backgroundColor = “”;
</html> })

9
SVG (Scalable Vector Graphics)
HTML
● SVG is a XML format used for drawing. <!DOCTYPE html>
<html>
<head>
● Similar to DOM, SVG has elements with parents, children <title>TITLE GOES HERE</title>
</head>
and attributes. <body>
<svg width=”300” height=”180”>
<circle cx=”30” cy=”50” r=”25” />
○ The elements also respond to the same mouse/touch <circle cx=”90” cy=”50” r=”25” class=”red” />
<circle cx=”150” cy=”50” r=”25” class=”fancy” />
events.
<rect x=”10” y=”80” width=”40” height=”40” fill=”steelBlue” />
<rect x=”70” y=”80” width=”40” height=”40” style=”fill: steelBlue;” />
● SVG defines tags for lots of basic shapes: <rect x=”130” y=”80” width=”40” height=”40” class=”fancy” />
</svg>
○ <rect> for rectangles </body>
</html>

○ <circle> for circles

○ <line> for straight lines


CSS
● Some CSS syntax used for DOM are different for SVG
elements. .red {
fill: red; /* not background-
color */
○ e.g., background-color: red; → fill: red; }

.fancy {
fill: none;
stroke: black;
stroke-width: 3pt;
stroke-dasharray: 3,5,10;
}
10
SVG - Groups
● Grouping elements:
○ DOM: <div> and <span> tags

○ SVG: <g> tag

● The tag <g> is widely used to create graphs in d3


○ to apply styles or reposition all the elements of a group at once.

<svg viewBox="0 0 100 100" >


<!-- Using g to inherit presentation attributes -->
<g fill="white" stroke="green" stroke-width="5">
<circle cx="40" cy="40" r="25" />
<circle cx="60" cy="60" r="25" />
</g>
</svg>

11
SVG - Paths
The <path> tag

● Powerful (and complex)


● It can be used for drawing lines or arbitrary shapes
● Largely used with d3 to create graphs (e.g., pie charts, line charts, etc)
○ d3 provides methods to automatically create the paths according to the data

<svg width="300" height=”100” >


<g transform="translate(5, 15)">
<text x=”0” y=”0”>Howdy!</text>
</g>
<g transform=”translate(5,55)”>
<!-- M: move to (jump)
L: line to
Q: quadratic curve to -->
<path d=”M0,50 L50,0 Q100,0 100,50” fill=”none” stroke-
width:”3” stroke=”black” />
</g>
<g transform=”translate(5, 105)”>
<!-- C: curve to (cubic)
Z: close shape -->
<path d=”M0,100 C0,0 25,0 125,100 z” fill=”black” />
</g> Note: The transform attribute allows to
</svg>
move, rotate, scale, etc., elements.
12
How to create a chart?

● Chart Elements
○ The Data
○ The Scales
○ The Axes

● Using SVG
● Using D3
○ Helpers
○ Defining the Scales
○ Defining the Axes
○ Binding the Data

13
Chart Elements
● The Scale: refers to the coordinate system
○ x-axis: from January 2014 to April 2014
○ y-axis: from $10 to $80
○ SVG dimensions: 350 by 160 pixels
■ Specify the mapping between data (i.e. values of variables) and pixels of the
screen
○ Note: y-axis flips as the SVG origin (i.e. the coordinates 0, 0) is in the top left

● The Axes: refer to the labels


○ Labels such as “$20” and “February” have to get to our screen somehow. Default coordinate system

○ They also need to be formatted correctly according to the data type.


● The Data
○ Each row of our dataset will become a point over the line.
○ The points in the line must fit into the defined coordinate system.

14
Using SVG
● Points and lines are drawn manually using SVG tags
○ The <path> tag is complex to be used by hand

15
<!DOCTYPE html>
<html>
<head>

Using D3
<title>TITLE GOES HERE</title>
</head>
<body>
<svg></svg>
</body>
</html>

1. Define the dataset. The data is always represented as var data = [


plain Javascript array objects. { date: “2014-01-01”, amount:10 },
{ date: “2014-02-01”, amount:20 },
{ date: “2014-03-01”, amount:40 },
{ date: “2014-04-01”, amount:80 }
]

var margin = {
2. Define the dimensions of the chart left: 20,
top: 10,
bottom: 20,
right: 10
}, // the margins of the chart
width = 350, // the width of the svg
height = 160; // the height of the svg

3. Set the SVG dimensions var svg = d3.select("svg")


.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)

var chartGroup = svg.append("g")


4. Create the chart group using the <g> tag .attr('transform', "translate(" + margin.left + "," + margin.top + ")")

16
Using D3 – Helpers (selections)

● D3 selections are a group of elements that match a query or could match a query later (the
elements may not have been constructed yet).
● How to:
○ d3.select(<key>) will find one element
■ typically using the element’s unique identifier
○ d3.selectAll(<key>) will match all available elements
■ typically used to select elements with a same class or name

17
Using D3 – Helpers (min, max, extent)
● Automate operations such as finding the minimum and maximum values of a dataset (or both at the same time, the
“extent”).
● The data is always represented as Javascript array objects
var values = [10, 20, 40, 80],
data = [
{ date: “2014-01-01”, amount:10 },
{ date: “2014-02-01”, amount:20 },
{ date: “2014-03-01”, amount:40 },
{ date: “2014-04-01”, amount:80 }
]

d3.min(values)
// 10

● When working with JSON objects, we use callback functions to recover the values we want to use in the helper
method.
○ The callback function has normally two arguments: the element and its index.
○ These arguments are commonly named d and i, respectively.

d3.max(values)
// 80
d3.max(data, (d,i) => d.amount)
// 80

d3.extent(values)
// [10, 80]
d3.extent(data, (d,i) => d.amount)
// [10, 80]
18
Using D3 – Defining the Scales
● d3-scale module (https://observablehq.com/@d3/introduction-to-d3s-scales) : map values across coordinate systems

● Types of scales: linear, logarithmic, time

● Scales are configured with a domain and a range:


○ they map values from the data (the domain) to the appropriate part of the screen (screen space -- the range in pixels).

var yScale = d3.scaleLinear()


.domain([0, 80]) // $0 to $80
.range([height, 0]) // seems backwards because SVG is y-down

● Defining the domain with helpers:

yScale.domain(d3.extent(data, d => d.amount)

● The object yScale is a function


○ We use it to translate values from one coordinate to another (i.e. between domain and range values):

yScale(10); // in: $10


// 200 // out: 200px (bottom of graph)

yScale(80); // in: $80


// 0 // out: 0px (top of graph)
19
Using D3 – Defining Scales (for time)
● The same things with dates!

var xScale = d3.scaleTime()


.domain([
new Date("2014-01-01"),
new Date("2014-04-01")
])
.range([0, width])

xScale(new Date("2014-02-01"))
// 124 // out: 124px

● Scales are not just for linear transforms (continuous or quantitative scales), but also for
arbitrary transforms (discrete or ordinal scales)
○ e.g., mapping between data and colors.

20
Using D3 – Defining the Axes
● We want labels and thick marks:
○ d3 can handle this automatically.
● When building an axis object, we give to it the scale we want to use as argument to the function.

var xAxis = d3.axisBottom(xScale)


.ticks(4)
.tickFormat(d3.timeFormat("%b"))

var yAxis = d3.axisLeft(yScale)


.ticks(4);

chartGroup.append("g")
.attr('transform', "translate(0, 0)")
.classed('y-axis', true)
.call(yAxis)

chartGroup.append("g")
.attr('transform', "translate(0," + height + ")")
.classed('x-axis', true)
.call(xAxis)
21
Using D3 – Data Binding
Data binding might require the following operations:
● Selections:
○ var selection = d3.selectAll(<key>)
● Joining the data:
○ selection.data(<data-object>): for binding data to multiple elements
○ selection.datum(<data-object>): for binding data to a single element
● Creating elements
○ selection.enter()
○ selection.append(<element-name>): when data won’t change
○ selection.join() (v5+): when data update is required (i.e. filters)
● Transitions
○ selection.transition()
○ selection.duration(<time-milliseconds>)
● Tooltips
22
Using D3 – Data Binding

Diagram by Leon T. Johnson


23
Using D3 – Data Binding (data)
● We use selections to map pieces of our data to elements in the DOM.
● We want to display the data as a line chart. We want each object to be a circle and to connect them
with lines. Thus, (1) each object would become a <circle> tag, inside of our <g> tag:

<!-- after -->


<svg>
<!-- before --> <g>
<svg> <g class=”x-axis”></g>
<g> <g class=”y-axis”></g>
<g class=”x-axis”></g> <circle /> <!-- {date: "2014-01-01", amount: 10} -->
<g class=”y-axis”></g> <circle /> <!-- {date: "2014-02-01", amount: 20} -->
</g> <circle /> <!-- {date: "2014-03-01", amount: 40} -->
</svg> <circle /> <!-- {date: "2014-04-01", amount: 80} -->
</g>
</svg>

● We select the <g> element and bind our data using the data(<data-obj>) function:
var svg = d3.select("svg")
.attr('width', width + margin.left + margin.right) var circles = chartGroup.selectAll(“circle”)
.attr('height', height + margin.top + margin.bottom) .data(data);

var chartGroup = svg.append("g") circles.size() // 0 -- not <circle> tag exists yet!


.attr('transform', "translate(" + margin.left + "," +
margin.top + ")")

Now we have a selection but still no elements! We have more work to do…
24
Using D3 – Data Binding (enter)

● Goal: one circle per data record.

● We add a new <circle> tag for each data point.

● Since this is the first data binding (there are no circles in the page yet), the process is straightforward.
○ Note: For the next selection, we must handle the fact that there will already be circles drawn on the page.

● We use selection.enter(), to indicate that we want to add new elements to the page.

var newCircles = circles.enter();

25
Using D3 – Data Binding (append / join)
● Then, we we use selection.append(<key>) or selection.join(<key>) to add these new elements.

newCircles.join("circle") newCircles.append("circle")
.attr("cx", d => xScale(new Date(d.date))) .attr("cx", d => xScale(new Date(d.date)))
.attr("cy", d => yScale(d.amount)) .attr("cy", d => yScale(d.amount))
.attr("r", 5) .attr("r", 5)
.style("fill", "steelblue") .style("fill", "steelblue")

chartGroup.selectAll("circle") chartGroup.selectAll("circle")
.data(data) .data(data)
.join("circle") .enter()
.attr("cx", d => xScale(new Date(d.date))) .append("circle")
.attr("cy", d => yScale(d.amount)) .attr("cx", d => xScale(new Date(d.date)))
.attr("r", 5) .attr("cy", d => yScale(d.amount))
.style("fill", "steelblue") .attr("r", 5)
.style("fill", "steelblue")

26
Using D3 – Data Binding (datum)
● We create a line through a path created with all the points in the data.

var lineGenerator = d3.line()


.x(d => xScale(new Date(d.date)))
.y(d => yScale(d.amount))

// Add the line


chartGroup.append("path")
.datum(data)
.attr(“class”, “line”)
.attr("fill", "none")
.attr("stroke", "steelblue")
.attr("stroke-width", 1.5)
.attr("d", lineGenerator)

27
Using D3 – Data Binding (data update)
1. If we have more data, we add new elements
2. If we have less data, we remove the elements that do not correspond to the new data we want to join in our chart
3. We update the elements attributes and style according to the new data

chartGroup.selectAll("circle")
var data = [ .data(data)
{ date: “2014-01-01”, amount:10 }, .join(
{ date: “2014-02-01”, amount:20 }, enter => enter.append(“circle”)
{ date: “2014-03-01”, amount:40 }, .attr("r", 5)
{ date: “2014-04-01”, amount:80 } .style("fill", "steelblue"),
] update => update,
exit => exit.remove()
)
.attr("cx", d => xScale(new Date(d.date)))
data.pop() .attr("cy", d => yScale(d.amount))

chartGroup.selectAll("path.line")
// [{ date: “2014-01-01”, amount:10 },
.attr("d", lineGenerator(data))
// { date: “2014-02-01”, amount:20 },
// { date: “2014-03-01”, amount:40 }]

28
Using D3 – Data Binding (Transitions)
● The operation selection.transition() allows temporal transitions to make transitions nicer.
● We can use attributes such as .duration(), .delay() and .ease(). We typically start by defining the duration to our
transition:

chartGroup.selectAll("circle")
.data(data)
.enter()
.join(
enter => enter.append(“circle”)
.attr("r", 5)
.style("fill", "steelblue"),
update => update,
exit => exit.remove()
)
.transition()
.duration(500)
.attr("cx", d => xScale(new Date(d.date)))
.attr("cy", d => yScale(d.amount))

chartGroup.selectAll("path.line")
.transition()
.duration(500)
.attr("d", lineGenerator(data))

29
Using D3 – Data Binding (Tooltips)
● We must often provide the user with more information than what is being visually represented, such as the actual values of the
represented variables
● We use then tooltips activated with mouseover and mouseout listeners that we add to our elements:
CSS
HTML
.tooltip{
<div class="tooltip"> </div> position: absolute;
z-index: 1000; /* to be in front of all other elements */
display: none; /* initially invisible */
background-color: #fff;
box-shadow: 10px 5px 5px #ccc;
border-radius: 5px;
}

D3.js
chartGroup.selectAll("circle")
.on("mouseover", function(d){
var x = d3.event.pageX,
y = d3.event.pageY;

d3.select("div.tooltip")
.style("display", "block")
.style("left", x + "px")
.style("top", y + "px")
.html("Date: " + d.date + "<br>" + "Amount: " + d.amount)
})
.on("mouseout", function(d){
d3.select("div.tooltip").style("display", "none")
})

Working example: https://jsfiddle.net/amenin/yruefj3c/188/


30
References

● HTML + CSS + JavaScript:


○ https://www.w3schools.com/html/default.asp
○ https://www.w3schools.com/css/default.asp
○ https://www.w3schools.com/js/default.asp
● D3:
○ http://d3js.org/
○ https://www.d3-graph-gallery.com/

31

You might also like