d3_js tutorial presentation
TRANSCRIPT
-
8/10/2019 D3_js Tutorial Presentation
1/110
10
20
45
6
D3.js TutorialStrata Conference
February 26, 2013
Santa Clara
github.com/align
Download the
-
8/10/2019 D3_js Tutorial Presentation
2/110
10
20
45
6
Jrme CukierIndependent data visualizer
Scott MurrayAssistant Professor, DesignUniversity of San Francisco
github.com/align
Download the
-
8/10/2019 D3_js Tutorial Presentation
3/110
What is d3.js?
-
8/10/2019 D3_js Tutorial Presentation
4/110
-
8/10/2019 D3_js Tutorial Presentation
5/110
-
8/10/2019 D3_js Tutorial Presentation
6/110
D3 Page Template
-
8/10/2019 D3_js Tutorial Presentation
7/110
HTML
CSS
JS
SVG
DOM
Hypertext Markup Language
Cascading Style Sheets
JavaScript
Scalable Vector Graphics
The Document Object Model
all of the above == web standards
-
8/10/2019 D3_js Tutorial Presentation
8/110
HTML
CSS
JS
SVG
DOM
Hypertext Markup Language
Cascading Style Sheets
JavaScript
Scalable Vector Graphics
The Document Object Model
Learning D3 is a process of learning the web
-
8/10/2019 D3_js Tutorial Presentation
9/110
-
8/10/2019 D3_js Tutorial Presentation
10/110
What you need
A text editor,
The d3 library, Files for your code,
Recommended: a web server,
A browser.
-
8/10/2019 D3_js Tutorial Presentation
11/110
A text editor
There are a few options out there: textMate, eclipse
sublime text 2What you really need is an editor with syntax high
Constructs with d3 can become very intricate.
Personally, I like sublime text 2.
-
8/10/2019 D3_js Tutorial Presentation
12/110
-
8/10/2019 D3_js Tutorial Presentation
13/110
-
8/10/2019 D3_js Tutorial Presentation
14/110
A template for d3
My project
-
8/10/2019 D3_js Tutorial Presentation
15/110
A template for d3
Start by specifying the doctype, to be in HTML5 mode (less suprises).
-
8/10/2019 D3_js Tutorial Presentation
16/110
A template for d3
An HTML tag is not required, but makes things more legible for people.
-
8/10/2019 D3_js Tutorial Presentation
17/110
A template for d3
Likewise, head and body tags are not required, but make things easier to read.
-
8/10/2019 D3_js Tutorial Presentation
18/110
A template for d3
It's better to specify a content type, this will allow you to use non-ascii characters wit
-
8/10/2019 D3_js Tutorial Presentation
19/110
A template for d3
My project
You may name your project here.
-
8/10/2019 D3_js Tutorial Presentation
20/110
A template for d3
My project
That's where you link to the d3 library. Here I am assuming it is in a folder one levelAlternatively, you can use http://d3js.org/d3.v2.min.js.
http://d3js.org/d3.v2.min.jshttp://d3js.org/d3.v2.min.js -
8/10/2019 D3_js Tutorial Presentation
21/110
A template for d3
My project
Optionally, you can link to a stylesheet like so. Or specify style inside a elem
-
8/10/2019 D3_js Tutorial Presentation
22/110
-
8/10/2019 D3_js Tutorial Presentation
23/110
My project
Finally, we link to a script file containing our actual javascript code.Alternatively, we may write our code here inside a element.
-
8/10/2019 D3_js Tutorial Presentation
24/110
A template for d3
My project
-
8/10/2019 D3_js Tutorial Presentation
25/110
Now let's look at a sample js file
var w=960,h=500;var svg=d3.select("#chart")
.append("svg") .attr("width",w).attr("height",h);
svg .append("text") .text("hello world!").attr("x",100).attr("y",100);
-
8/10/2019 D3_js Tutorial Presentation
26/110
Now let's look at a sample js file
var w=960,h=500;
Simple variables to size the vis.Those numbers are chosen because they work well with Mike Bostock's http://bl.ockviewer for code examples hosted onGitHub Gist.
https://gist.github.com/https://gist.github.com/https://gist.github.com/https://gist.github.com/https://gist.github.com/https://gist.github.com/http://bl.ocks.org/http://bl.ocks.org/ -
8/10/2019 D3_js Tutorial Presentation
27/110
Now let's look at a sample js file
var w=960,h=500;var svg=d3.select("#chart")
Now we are going to create an SVG container. It will be a child of the div named #chcreated earlier.
-
8/10/2019 D3_js Tutorial Presentation
28/110
Now let's look at a sample js file
var w=960,h=500;var svg=d3.select("#chart")
.append("svg")
This creates the svg element per se.
-
8/10/2019 D3_js Tutorial Presentation
29/110
Now let's look at a sample js file
var w=960,h=500;var svg=d3.select("#chart")
.append("svg") .attr("width",w).attr("height",h);
And this last line gives an explicit width and height to the svg element. This is desirechrome/safari, the svg just resizes as needed) and generally more proper.
-
8/10/2019 D3_js Tutorial Presentation
30/110
Now let's look at a sample js file
var w=960,h=500;var svg=d3.select("#chart")
.append("svg") .attr("width",w).attr("height",h);
svg .append("text")
Now that we have an SVG container, we can just add any kind of SVG element to it. with text.
-
8/10/2019 D3_js Tutorial Presentation
31/110
Now let's look at a sample js file
var w=960,h=500;var svg=d3.select("#chart")
.append("svg") .attr("width",w).attr("height",h);
svg .append("text") .text("hello world!").attr("x",100).attr("y",100);
This last line specifies characteristics of the element we've just added.
-
8/10/2019 D3_js Tutorial Presentation
32/110
A sample js file.
var w=960,h=500;var svg=d3.select("#chart")
.append("svg") .attr("width",w).attr("height",h);
svg .append("text") .text("hello world!").attr("x",100).attr("y",100);
-
8/10/2019 D3_js Tutorial Presentation
33/110
Lo and behold:
-
8/10/2019 D3_js Tutorial Presentation
34/110
A web server
You can view most d3 visualizations locally, simply
opening an html file in a browser. But if your visualization is reading data from files o
database (XMLHttpRequest), then you need to publweb server to test it.
There are many options: EasyPHP (windows), Mac
Server, MAMP (Mac OS X)
-
8/10/2019 D3_js Tutorial Presentation
35/110
-
8/10/2019 D3_js Tutorial Presentation
36/110
ll b
-
8/10/2019 D3_js Tutorial Presentation
37/110
Finally, a browser
-
8/10/2019 D3_js Tutorial Presentation
38/110
Th l
-
8/10/2019 D3_js Tutorial Presentation
39/110
The console
-
8/10/2019 D3_js Tutorial Presentation
40/110
-
8/10/2019 D3_js Tutorial Presentation
41/110
Selecting elements
Exercise: Create this web page by typing D3 c
-
8/10/2019 D3_js Tutorial Presentation
42/110
into the console.
Strata TutorialD3 can be used to generate new DOM e
Get it from d3js.org!
h1
p
a
-
8/10/2019 D3_js Tutorial Presentation
43/110
-
8/10/2019 D3_js Tutorial Presentation
44/110
Data joins with d3
Strata d3 tuto
Where's the data?
-
8/10/2019 D3_js Tutorial Presentation
45/110
Where's the data?
So far we've been adding elements one by on
Let's put the data in data visualization!
Introducting selectAll
-
8/10/2019 D3_js Tutorial Presentation
46/110
Introducting selectAll
selectAll allows you to select all elements that corres
condition, and manipulate them all at once.
d3.selectAll("p").style("font-weight","bold");
Here's how it works:
-
8/10/2019 D3_js Tutorial Presentation
47/110
Here's how it works:
All existing elements
-
8/10/2019 D3_js Tutorial Presentation
48/110
What just happened?
-
8/10/2019 D3_js Tutorial Presentation
49/110
What just happened?
existing elements Dodata
Side note: who is d?
-
8/10/2019 D3_js Tutorial Presentation
50/110
Side note: who is d?
Here I wrote:.style("font-size",function(d) {return d;})
What is d?Here, I'm assigning to the "font-size" style a value which is not static, To compute that value, we retrieve it from the data using functions.The first argument of these functions is the data item. The name of this arbitrary, d is a convention.
Here, we just return the value we've read, but inside the function theany kind of transformation.
Side note: can I use existing functions ins
-
8/10/2019 D3_js Tutorial Presentation
51/110
retyping them each time?
YES!!
For instance, String(123) converts a number into a string.Conveniently, it also converts a string into a string.In most cases, String(d) is equivalent to function(d) {return d;
So instead of .style("font-size",function(d) {return d;})
We can write: .style("font-size",String)
Creating new elements from da
-
8/10/2019 D3_js Tutorial Presentation
52/110
Creating new elementsfrom da
With selectAll, we've seen we can manipulate existinelements.
With selectAll then data, we've seen that we can manexisting elements dynamically, using data.
Now what if there are no existing elements?
Introducing enter
-
8/10/2019 D3_js Tutorial Presentation
53/110
Introducing enter
If you find yourself in this situation
existing elements data
Introducing enter
-
8/10/2019 D3_js Tutorial Presentation
54/110
Introducing enter
d3.select("body").selectAll("p").data(data).enter()
will create "pods" for future elements
elements data
Introducing enter
-
8/10/2019 D3_js Tutorial Presentation
55/110
Introducing enter
....selectAll("p").data(data).enter().append("p")
Then append will create as many elements as needeopposed to just one.
elements data
-
8/10/2019 D3_js Tutorial Presentation
56/110
-
8/10/2019 D3_js Tutorial Presentation
57/110
Side note: what happens if the data cha
-
8/10/2019 D3_js Tutorial Presentation
58/110
pp
So you created a bunch of elements dynamically, usi
Then, for some reason, the data changes.What happens to your elements?
Side note: what happens if the data cha
-
8/10/2019 D3_js Tutorial Presentation
59/110
pp
So you created a bunch of elements dynamically, usi
Then, for some reason, the data changes.What happens to your elements?Nothing, unless you also change their attributes.
(BTW this is different from protovis, the ancestor o
How do I remove elements?
-
8/10/2019 D3_js Tutorial Presentation
60/110
The remove() method can be attached to any selectio
d3.selectAll("p").remove()
Effectively deletes all paragraphs found in the docum
-
8/10/2019 D3_js Tutorial Presentation
61/110
Working with a smaller dataset
-
8/10/2019 D3_js Tutorial Presentation
62/110
g
Only the first element changes. The other two are lefuntouched.
elements data
How do I remove someelement
-
8/10/2019 D3_js Tutorial Presentation
63/110
In order to capture the elements which are no longeby a data point, we can use the method exit():
d3.selectAll("p").data(["hello world"]).exit()// do stuff to those, often .remove();
Exercise: Create four span elements with the
text and colors.
-
8/10/2019 D3_js Tutorial Presentation
64/110
darkmagentatealrosybrownmidnightbspan
HINT: var colors = [darkmagenta , teal ,
rosybrown ,
midnightblue
-
8/10/2019 D3_js Tutorial Presentation
65/110
-
8/10/2019 D3_js Tutorial Presentation
66/110
-
8/10/2019 D3_js Tutorial Presentation
67/110
-
8/10/2019 D3_js Tutorial Presentation
68/110
Scales with d3
Strata d3 tuto
-
8/10/2019 D3_js Tutorial Presentation
69/110
Introducing scales
-
8/10/2019 D3_js Tutorial Presentation
70/110
Scales are a family of d3 methods forsimple algebraic transformations.Here's onevar myScale=d3.scale.linear().domain([0,25]) .range([0,100]);myScale(0) // 0
myScale(25) // 100myScale(10) // 40
Wait!
-
8/10/2019 D3_js Tutorial Presentation
71/110
var myScale=d3.scale.linear().domain([0,25])
.range([0,100]);
Isn't that the same as just multiplying by 4?And if so, why would I care?
Advantages of a scale
-
8/10/2019 D3_js Tutorial Presentation
72/110
it's very easy to change its parameters.
If you are changing the size of the elementswithout a scale you'd have to change every possiblof the hard coded calculations.
.attr("y", function(d) { return h - (d * 4); })
.attr("height", function(d) { return d * 5;})This is very error-prone.
Using scales can lead to nice, compact yetcode
-
8/10/2019 D3_js Tutorial Presentation
73/110
var y=d3.scale.linear().range([0,100]).domain([0,25]);
. .attr("y",y)
Using scales can lead to nice, compact yetcode
-
8/10/2019 D3_js Tutorial Presentation
74/110
var y=d3.scale.linear().range([0,100]).domain([0,25]);
. .attr("y",y)
There are several other types of scales:
log sqrt power
-
8/10/2019 D3_js Tutorial Presentation
75/110
So
-
8/10/2019 D3_js Tutorial Presentation
76/110
What's the sweet spot between using scales (which mhaving to write scales in full once) and writing out fu
quickly that do equivalent things?
So
-
8/10/2019 D3_js Tutorial Presentation
77/110
My recommendation:
Always.
Use.
Scales.
Ordinal scales
-
8/10/2019 D3_js Tutorial Presentation
78/110
So far we have seen quantitative scales, which transfnumber into another number.
But there are also ordinal scaleswhich turn associateitems with a value.
-
8/10/2019 D3_js Tutorial Presentation
79/110
rangePoints
-
8/10/2019 D3_js Tutorial Presentation
80/110
myScale=d3.scale.ordinal()
.domain(["Monday","Tuesday","Wednesday","Thursday,"Saturday","Sunday"]).rangePoints([0,100])
myScale("Tuesday")
Interesting ordinal scales: color palett
-
8/10/2019 D3_js Tutorial Presentation
81/110
In d3, color palettes are really ordinal scales, since thassociate discrete values with values.
There are a few built in ones:d3.scale.category10()
//d3.scale.category10()("a") //
-
8/10/2019 D3_js Tutorial Presentation
82/110
-
8/10/2019 D3_js Tutorial Presentation
83/110
Transitions
// Transitions and motion
-
8/10/2019 D3_js Tutorial Presentation
84/110
-
8/10/2019 D3_js Tutorial Presentation
85/110
Interaction with d3
Visweek d3 worksh
Two broad types of interaction with
-
8/10/2019 D3_js Tutorial Presentation
86/110
Forms
And it doesnt have to be a full-fledged form: controlsdown menus, tick boxes, sliders etc.
Interaction on elements of the chart properSVG or HTML elements: clicking, moving the cursor inetc.
Good news!
-
8/10/2019 D3_js Tutorial Presentation
87/110
While they may look different, they both really worksame.
And its not super complicated.
-
8/10/2019 D3_js Tutorial Presentation
88/110
Here's an example
-
8/10/2019 D3_js Tutorial Presentation
89/110
var w=960,h=500,flag=0;
-
8/10/2019 D3_js Tutorial Presentation
90/110
var w=960,h=500,flag=0;var svg=d3.select("#chart").append("svg").attr("width",w).attr("height",h);
var myRect=svg
.append("rect").attr({x:100,y:100,width:100,height:100}) .style("fill","steelblue");
-
8/10/2019 D3_js Tutorial Presentation
91/110
var w=960,h=500,flag=0;var svg=d3.select("#chart").append("svg").attr("width",w).attr("height",h);
var myRect=svg
.append("rect").attr({x:100,y:100,width:100,height:100}) .style("fill","steelblue");
myRect.on("click",function() {
})
-
8/10/2019 D3_js Tutorial Presentation
92/110
var w=960,h=500,flag=0;var svg=d3.select("#chart").append("svg").attr("width",w).attr("height",h);
var myRect=svg
.append("rect").attr({x:100,y:100,width:100,height:100}) .style("fill","steelblue");
myRect.on("click",function() {
flag=1-flag; myRect.style("fill", flag?"darkorange":"steelblue");
})
on + event + function
-
8/10/2019 D3_js Tutorial Presentation
93/110
That's the general gist of it.
There are few events you should know.
"click"is the workhorse of events. Click anything (atext, a shape) and things happen."mouseover", "mouseout" are other good ones.Great for highlighting stuff and all.
"change" is great for forms (the value of the form ch
Going further: events on group
-
8/10/2019 D3_js Tutorial Presentation
94/110
By setting an event listener on a "g" element, it will btriggered by any interaction on any element of that g
Going further: events and data
-
8/10/2019 D3_js Tutorial Presentation
95/110
Can the function access the underlying data of the elcourse!
If the element has data tied to it, you can do
myElement.on("click",function(d) { // operations on data
})
Going further: playing with form
ll h f f l h
-
8/10/2019 D3_js Tutorial Presentation
96/110
Usually the point of form controls is to access the vaselected by the user. So you'll often have something
myControl.on("change",function() { doStuff(this.value);})
-
8/10/2019 D3_js Tutorial Presentation
97/110
-
8/10/2019 D3_js Tutorial Presentation
98/110
http://bl.ocks.org/3739100
http://bl.ocks.org/3739100http://bl.ocks.org/3739100http://bl.ocks.org/3739100http://bl.ocks.org/3739100http://bl.ocks.org/3739100http://bl.ocks.org/3739100 -
8/10/2019 D3_js Tutorial Presentation
99/110
Let's see how it looks like in the cod
d3 select("#gores") on("change" function() {
-
8/10/2019 D3_js Tutorial Presentation
100/110
d3.select("#gores").on("change", function() {
gores();
});
function gores() {
var n = +d3.select("#gores").property("value");
}
-
8/10/2019 D3_js Tutorial Presentation
101/110
-
8/10/2019 D3_js Tutorial Presentation
102/110
http://bl.ocks.org/3709000
Let's see how it looks like in the cod
var projection = svg.selectAll(".axis text,.background path,.foreground path")
http://bl.ocks.org/3709000http://bl.ocks.org/3709000http://bl.ocks.org/3709000http://bl.ocks.org/3709000http://bl.ocks.org/3709000http://bl.ocks.org/3709000 -
8/10/2019 D3_js Tutorial Presentation
103/110
var projection svg.selectAll( .axis text,.background path,.foreground path )
.on("mouseover", mouseover)
.on("mouseout", mouseout);
function mouseover(d) { svg.classed("active", true);
projection.classed("inactive", function(p) { return p !== d; });
projection.filter(function(p) { return p === d; }).each(moveToFront);
}
function mouseout(d) {
svg.classed("active", false);
projection.classed("inactive", false);
}
function moveToFront() {
this.parentNode.appendChild(this);
}
-
8/10/2019 D3_js Tutorial Presentation
104/110
-
8/10/2019 D3_js Tutorial Presentation
105/110
-
8/10/2019 D3_js Tutorial Presentation
106/110
Whats next?
// Generate axes
var axis = d3.svg.axis()
scale(scale);
-
8/10/2019 D3_js Tutorial Presentation
107/110
.scale(scale);
svg.append("g") .call(axis);
200 300 400 500 600 700 800
// Layouts
-
8/10/2019 D3_js Tutorial Presentation
108/110
// Geomapping and projections
-
8/10/2019 D3_js Tutorial Presentation
109/110
-
8/10/2019 D3_js Tutorial Presentation
110/110