A short introduction of D3js

69
D3JS JAN. 2013 DREAMPUF

description

## Agenda - Introduction - Examples - A guide of bar chart - The analysis of source code - The Wealth & Health of Nations - An time series visual design of Adserver svn commit record - Resources

Transcript of A short introduction of D3js

Page 1: A short introduction of D3js

D3JS JAN. 2013DREAMPUF

Page 2: A short introduction of D3js

AGENDAIntroduction

Examples

A guide of bar chart

The analysis of source code

The Wealth & Health of Nations

An time series visual design of Adserver svn commit

record

Resources

Page 3: A short introduction of D3js

INTRODUCTION

Page 4: A short introduction of D3js

D3.JS: DATA-DRIVEN DOCUMENTS

JavaScript Library

Open source (BSD license)

developed by Michael Bostock and others at Stanford

University

former work on Protovis Library

from Intro to d3

Page 5: A short introduction of D3js

D3.JS: DATA-DRIVEN DOCUMENTS

not a traditional visualization framework

focus on efficient manipulation of documents based on

data

bind arbitrary data to the DOM

apply data-driven transformations to the document

functional/declarative style

support for interaction and animation

you have to do the graphical representation yourself!

but has helpers for SVG generation

from Intro to d3

Page 6: A short introduction of D3js

FEATURE

Page 7: A short introduction of D3js

SELECTIONS

operate on arbitrary sets of nodes called selectionsW3C Selectors API or Sizzle fallback

d3.selectAll("p") .style("color", "white");

Page 8: A short introduction of D3js

DYNAMIC PROPERTIES

bind data to a selectionapply functions to styles, attributes and otherpropertiesa lot of built-in reusable functions availablebound data available as first argumentyou can omit the data operator the second time!

d3.selectAll("p") .data([4, 8, 15, 16, 23, 42]) .style("font-size", function(d, i) { return d + "px"; });

Page 9: A short introduction of D3js

ENTER AND EXIT

enter: selects all data elements without a DOM

representation

exit: selects all DOM elements without data

common pattern

perform only necessary modifications

var p = d3.select("body").selectAll("p") // Update… .data([4, 8, 15, 16, 23, 42]) .text(String);p.enter().append("p") // Enter… .text(String);p.exit().remove(); // Exit…

Page 10: A short introduction of D3js

SUBSELECTIONS

generate a subselection by calling selectAll on anexisting selectionmaintains the hierarchical structure

d3.selectAll("ul") .data(questions) // an array of questions .selectAll("li") // a nested array of responses .data(function(d) { return d.responses; }) // the text of the response .text(function(d) { return d.text; });

Page 11: A short introduction of D3js

TRANSITIONS

with d3.js they are easy!various tweening functionsinterpolation of basic types, numbers and numbers instrings (e.g. "15px")

// fade background from white to black in 1sd3.select("body").transition() .duration(1000) .style("background-color", "black");

Page 12: A short introduction of D3js

EXAMPLES

Page 13: A short introduction of D3js

FISHER–YATES SHUFFLE

Page 14: A short introduction of D3js

2008 OLYMPIC MEDALS

Page 15: A short introduction of D3js

OBAMA'S 2013 BUDGET

PROPOSAL

Page 16: A short introduction of D3js
Page 17: A short introduction of D3js

00

55

1010

1515

2020

2525

3030

3535

4040

4545

economy (mpg)economy (mpg)

3.03.0

3.53.5

4.04.0

4.54.5

5.05.0

5.55.5

6.06.0

6.56.5

7.07.0

7.57.5

8.08.0cylinderscylinders

100100

150150

200200

250250

300300

350350

400400

450450

displacement (cc)displacement (cc)

00

2020

4040

6060

8080

100100

120120

140140

160160

180180

200200

220220

power (hp)power (hp)

2,0002,000

2,5002,500

3,0003,000

3,5003,500

4,0004,000

4,5004,500

5,0005,000

weight (lb)weight (lb)

88

1010

1212

1414

1616

1818

2020

2222

2424

0-60 mph (s)0-60 mph (s)

Page 18: A short introduction of D3js

flare

analytics

cluster

AgglomerativeCluster

CommunityStructure

HierarchicalCluster

MergeEdge

graph

BetweennessCentrality

LinkDistance

MaxFlowMinCut

ShortestPaths

SpanningTree

optim

ization

AspectRatioBanker

animate

Easing

FunctionSequence

interpolate

ArrayInterpolator

ColorInterpolator

DateInterpolator

Interpolator

MatrixInterpolator

NumberInterpolator

ObjectInterpolator

PointInterpolator

RectangleInterpolator

ISchedulable

Parallel

Pause

Scheduler

Sequence

Transition

Transitioner

TransitionEvent

Tween

data

converters

Converters

DelimitedTextConverter

GraphMLConverter

IDataC

onverter

JSON

Converter

DataF

ield

DataS

chem

a

DataS

et

DataS

ource

DataT

able

DataU

til

display

DirtySp

rite

LineSpri

te

flex

physics

query

vis

axis

controls

ClickCo

ntrolCon

trolControlL

istDragCon

trolExpandCo

ntrolHoverCon

trolIControlPanZo

omControlSelectio

nControlTooltipCo

ntrol

data

DataDataList

DataSpriteEdgeSpriteNodeSprite

renderArrowType

EdgeRenderer

IRenderer

ShapeRenderer

ScaleBindingTree

TreeBuilderevents

DataEvent

SelectionEvent

TooltipEvent

VisualizationEvent legend

Legend

LegendItem

LegendRange

operator

distortion

BifocalDistortion

Distortion

FisheyeDistortion encoder

ColorEncoder

Encoder

PropertyEncoder

ShapeEncoder

SizeEncoder

filter

FisheyeTreeFilter

GraphDistanceFilter

VisibilityFilte

r

IOperator

label

Labeler

RadialLabeler

Stacke

dAreaLabeler

layout

AxisLa

yout

BundledEdgeRouter

CircleLayout

CirclePackingLayout

DendrogramLayout

ForceDirectedLayout

IcicleTre

eLayout

IndentedTre

eLayout

Layout

NodeLin

kTreeLayout

PieLayout

RadialTre

eLayout

RandomLayout

StackedAreaLayout

TreeMapLayout

Operator

OperatorList

OperatorSe

quence

OperatorSw

itch

SortO

perator

Visualiza

tion

Page 19: A short introduction of D3js
Page 20: A short introduction of D3js
Page 21: A short introduction of D3js
Page 22: A short introduction of D3js

Aitoff

Page 23: A short introduction of D3js

TUTORIALSA GUIDE OF BAR CHART

Page 24: A short introduction of D3js

BASE COMPONENTHTML

CSS

Javascript

SVG

Page 25: A short introduction of D3js

SVG<svg width="50" height="50"></svg>

Page 26: A short introduction of D3js

SVG

<svg width="50" height="50"> <circle cx="25" cy="25" r="22" fill="blue" stroke="gray" stroke-width="2"/></svg>

Page 27: A short introduction of D3js

SIMPLE SHAPES

Page 28: A short introduction of D3js

SIMPLE SHAPES

<rect x="0" y="0" width="500" height="50"/>

Page 29: A short introduction of D3js

SIMPLE SHAPES

<circle cx="250" cy="25" r="25"/>

Page 30: A short introduction of D3js

SIMPLE SHAPES

<ellipse cx="250" cy="25" rx="100" ry="25"/>

Page 31: A short introduction of D3js

SIMPLE SHAPES

<line x1="0" y1="0" x2="500" y2="50" stroke="black"/>

Page 32: A short introduction of D3js

SIMPLE SHAPES

Easy-peasy<text x="250" y="25">Easy-peasy</text>

Page 33: A short introduction of D3js

SIMPLE SHAPES

Easy-peasy

<text x="150" y="50" font-family="sans-serif" font-size="50" fill="gray">Easy-peasy</text>

Page 34: A short introduction of D3js

SIMPLE SHAPES

<circle cx="25" cy="25" r="100" fill="yellow" stroke="orange" stroke-width="5"/>

Page 35: A short introduction of D3js

SIMPLE SHAPES

<circle cx="25" cy="25" r="22" class="pumpkin"/>

.pumpkin { fill: red; stroke: orange; stroke-width: 5; }

Page 36: A short introduction of D3js

SIMPLE SHAPES

<rect x="100" y="100" width="80" height="80" fill="purple"/><rect x="120" y="105" width="80" height="80" fill="blue"/><rect x="140" y="110" width="80" height="80" fill="green"/><rect x="160" y="115" width="80" height="80" fill="yellow"/><rect x="180" y="120" width="80" height="80" fill="red"/>

Page 37: A short introduction of D3js

SIMPLE SHAPES

<circle cx="125" cy="80" r="60" fill="rgba(128, 0, 128, 1.0)"/><circle cx="150" cy="80" r="60" fill="rgba(0, 0, 805, 0.75)"/><circle cx="175" cy="80" r="60" fill="rgba(0, 805, 0, 0.5)"/><circle cx="200" cy="80" r="60" fill="rgba(805, 805, 0, 0.80)"/><circle cx="280" cy="80" r="60" fill="rgba(805, 0, 0, 0.1)"/>

Page 38: A short introduction of D3js
Page 39: A short introduction of D3js

PAGE<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<title>D3 Test</title>

<script type="text/javascript" src="d3/d3.v3.js">&lt;/script>

</head>

<body>

<script type="text/javascript">

// Your beautiful D3 code will go here

&lt;/script>

</body>

</html>

Page 40: A short introduction of D3js

FIRSTd3.select("body").append("p").text("New paragraph!");

Page 41: A short introduction of D3js

WITH DATA

var dataset = [ 5, 10, 15, 20, 25 ];d3.select("body").selectAll("p");

Page 42: A short introduction of D3js

WITH DATA

d3.select("body").selectAll("p") .data(dataset) .enter() .append("p") .text("New paragraph!");

Page 43: A short introduction of D3js

WITH DATA

console.log(d3.selectAll("p"))

Page 44: A short introduction of D3js

WITH DATA

console.log(d3.selectAll("p"))

Page 45: A short introduction of D3js

WITH DATA

var dataset = [ 5, 10, 15, 20, 25 ];d3.select("body").selectAll("p") .data(dataset) .enter() .append("p") .text(function(d) { return d; });

Page 46: A short introduction of D3js
Page 47: A short introduction of D3js

BEYOND TEXT

.style("color", "red");

.style("color", function(d) { if (d > 15) { //Threshold of 15 return "red"; } else { return "black"; }});

Page 48: A short introduction of D3js

PLAY WITH DATA

var dataset = [ 25, 7, 5, 26, 11, 8, 25, 14, 23, 19,

14, 11, 22, 29, 11, 13, 12, 17, 18, 10,

24, 18, 25, 9, 3 ];

d3.select("body").selectAll("div")

.data(dataset) // <-- The answer is here!

.enter()

.append("div")

.attr("class", "bar")

.style("height", function(d) {

var barHeight = d * 5;

return barHeight + "px";

});

Page 49: A short introduction of D3js

MAKING A BAR CHART

var dataset = [ 5, 10, 13, 19, 21, 25, 22, 18, 15, 13, 11, 12, 15, 20, 18, 17, 16, 18, 23, 25 ];

Page 50: A short introduction of D3js

MAKING A BAR CHART

svg.selectAll("rect") .data(dataset) .enter() .append("rect") .attr("x", 0) .attr("y", 0) .attr("width", 20) .attr("height", 100);

Page 51: A short introduction of D3js

MAKING A BAR CHART

.attr("x", function(d, i) { return i * 21; //Bar width of 20 plus 1 for padding})

Page 52: A short introduction of D3js

MAKING A BAR CHART

.attr("height", function(d) { return d;});

Page 53: A short introduction of D3js

MAKING A BAR CHART

.attr("y", function(d) {

return h - d; //Height minus data value

})

.attr("height", function(d) {

return d * 4; //Just the data value

});

Page 54: A short introduction of D3js

MAKING A BAR CHART

.attr("fill", function(d) { return "rgb(0, 0, " + (d * 10) + ")";});

Page 55: A short introduction of D3js

MAKING A BAR CHART

svg.selectAll("text") .data(dataset) .enter() .append("text") .text(function(d) { return d; }) .attr("text-anchor", "middle") .attr("x", function(d, i) { return i * (w / dataset.length) + (w / dataset.length - barPadding) / 2; }) .attr("y", function(d) { return h - (d * 4) + 14; }) .attr("font-family", "sans-serif") .attr("font-size", "11px") .attr("fill", "white");

Page 56: A short introduction of D3js

THE ANALYSIS OFSOURCE CODE

Page 57: A short introduction of D3js

THE WEALTH & HEALTH OF NATIONS

Page 58: A short introduction of D3js

DATA[{ "name": "Angola", "region": "Sub-Saharan Africa", "income": [ [1800, 359.93], [1820, 359.93], [1913, 556.12], [1950, 3363.02], [1951, 3440.9], [1952, 3520.61], [1953, 3598.81], [1954, 3450.82], [1955, 3672.08], [1956, 3549.04],

Page 59: A short introduction of D3js

TRANSITION

// Start a transition that interpolates the data based on year.svg.transition() .duration(duration) .ease("linear") .tween("year", tweenYear()) .each("end", enableInteraction);

// Tweens the entire chart by first tweening the year, and then the data.// For the interpolated data, the dots and label are redrawn.function tweenYear(start, end) { start = start || 1800; end = end || 2009; return function() { var year = d3.interpolateNumber(start, end); return function(t) { displayYear(year(t)); }; }}

Page 60: A short introduction of D3js

INTERPOLATE DATA

// Interpolates the dataset for the given (fractional) year.function interpolateData(year) { return nations.map(function(d) { return { name: d.name, income: interpolateValues(d.income, year), //... }; });}

// Finds (and possibly interpolates) the value for the specified year.function interpolateValues(values, year) { var i = bisect.left(values, year, 0, values.length - 1), a = values[i]; if (i > 0) { var b = values[i - 1], t = (year - a[0]) / (b[0] - a[0]);

Page 61: A short introduction of D3js

ADSERVER SVN COMMIT RECORD

Page 62: A short introduction of D3js

DATA"total": [ [1303115788, 2], [1303182050, 6], [1303194454, 18], [1303210228, 28], [1303267612, 40], //...],"qwang": [ [1335869108, 0], [1335869108, 9], [1335869340, 2], [1335954367, 33], //...

Page 63: A short introduction of D3js

LAYOUT

force = d3.layout.force() .gravity(.5) .charge(function(d, i){ return i ? 0 : -20; }) .nodes(users) .size([width, height]);

force.start();force.on("tick", function(e) { var q = d3.geom.quadtree(users), i = 0, n = users.length;

while (++i < n) { q.visit(collide(users[i])); }

dot.selectAll("g") .attr("transform", function(d) { return "translate(" + d.x + ", "

Page 64: A short introduction of D3js

COLLISION

function collide(node) { var rr = r(node), nx1 = node.x - rr, nx2 = node.x + rr, ny1 = node.y - rr, ny2 = node.y + rr; return function(quad, x1, y1, x2, y2) { if (quad.point && (quad.point !== node)) { var x = node.x - quad.point.x, y = node.y - quad.point.y, l = Math.sqrt(x * x + y * y), rr = r(node) + r(quad.point); if (l < rr) { l = (l - rr) / l * .5; node.x -= x *= l; node.y -= y *= l; quad.point.x += x; quad.point.y += y;

Page 65: A short introduction of D3js

RESUMEfunction displayDay(time_pos) { dots.data(interpolateData(time_pos)).call(position).sort(order); label.text(secondtoday(time_pos)); force.resume();}

Page 66: A short introduction of D3js

RESOURCES

Page 67: A short introduction of D3js

RESOURCES

D3js WikiPaper:D3: Data-Driven DocumentsMike BostockVisual.lyDavid McCandless: The beauty of data visualizationGapMinder - for a fact-based world view

Page 68: A short introduction of D3js

Q & A

Page 69: A short introduction of D3js

THANK YOU