D3.js Tutorial

First Part


A tutorial by Dominik Moritz (@domoritz) and Kanit "Ham" Wongsuphasawat (@kanitw)

Interactive Data Lab, University of Washington

(Based on Vadim Ogievetsky and Scott Murray's work)

## Outline * Examples * Selections & Data * Transitions * Nested Selections Part 2: Interactions, scales, axes, data, layouts

Data-Driven Documents (D3)

What D3 is not

  • Not a chart library (but it can make charts)
  • Not a compatibility layer
  • Not (only) about SVG or HTML or Canvas

D3 is Data ↦ Elements

  • Visualizing Data with Web Standards (HTML/SVG)
  • Data ↦ Elements – constructing the DOM from Data
  • In visualization, each data point has a corresponding element (graphical marks). D3 helps you maintain this mapping!

Show Reels

See

Selections

D3 uses CSS Selectors

Single selector:

#foo        //  
foo         //  
.foo        //  
[foo=bar]   //  
foo bar     //  
          

Multiple selectors:

foo.bar     //  
foo#bar     //  
          

.select()

.select() + .attr(), .style()

Select and modify element properties

Note: notice chained syntax, object as argument

but .select() only selects one item!

.selectAll()

See also: http://mbostock.github.io/d3/tutorial/circle.html

.data()

Data ↦ Attributes

.data()

Tell D3 that you want the selected elements to correspond to data!

See in console that the selected rect selection object is an array of array that embed data in __data__ property!

Selection Object

  • An array of arrays
  • if .data() is called, __data__ of each element will contain the data mapped to that element.

You should have seen this from last slide!

.data()

Data can be objects too!

.data()

What if number of data doesn't match number of items selected?

Thinking with Join



DataEnterUpdateElementsExit

Calling .data() creates three arrays:

  • enter (Data without corresponding DOM elements)
  • update (DOM elements mapped to data)
  • exit (DOM elements now missing data)

.data() returns the update.


http://bost.ocks.org/mike/join/

.enter()

.enter()

Shorter: append, then update all together!

.enter() from scratch

This is a common way that people build visualization in D3!

.exit()

Transitions

.transition()

Note: Transitions in D3 use cubic-in-out as default easing functions. But there are others.

Nested .transition() & .delay()

Mapping Data to Elements

The default is index mapping.

Join key – .data(...,key)

A key should be a unique string.

http://bost.ocks.org/mike/selection/#key

Join key – .data(...,key)

Notice how you can save lines of code with selection.call()

http://bost.ocks.org/mike/selection/#key

Join key

New Data?

See even better bars transition.

See also

Nested Selections

Nested Selections

See also: How Selection Works

"Two Tables"

### More examples * [bl.ocks.org/mbostock/3887051](http://bl.ocks.org/mbostock/3887051) * [bost.ocks.org/mike/miserables/](http://bost.ocks.org/mike/miserables/)

2nd part of D3.js tutorial