D3.js Tutorial

Second 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 * Interactions * Scales & Axes * Tips e.g. Importing Data * Path Generators & Line Interpolators * Layouts & Maps * Let's Build a Chart & More Examples


Event Listeners

.on('mouseover',...), .on('click',...)

Note 1: :hover pseudo-selector also works with svg!

Note 2: To remove a listener, pass null as the listener. To remove all listeners for a particular event type, pass null as the listener, and .type as the type, e.g. selection.on(".foo", null).

SVG Tooltips

Last week, we did it in svg.

SVG Tooltips

HTML Tooltips

See "Div Tooltip HTML" in Murray

Brushing - d3.svg.brush()

From http://bl.ocks.org/mbostock/4063663. See also Focus+Context


Domain ↦ Range

So you don't have to write:

function x(d) {
  return d * 42 + "px";



var x = d3.scale.linear().domain([0, 10]).range([0,100]);
console.log(x(-1),x(0), x(4.4), x(10), x(11)); //-10 0 44 100 110 with some rounding errors
console.log(x.clamp()(-1), x.clamp()(11); // 0 100
Source: http://www.jeromecukier.net/blog/2011/08/11/d3-scales-and-color/

Scale methods

  • .nice() round domain to nicer numbers e.g. from [0.2014, 0.9966] to [0.2, 1]
    d3.scale.linear().domain([0.2014,0.9966]).nice().domain() // [0.1,1]
  • .rangeRound() output range in integers – better for positioning marks on the screen
    d3.scale.linear().domain([0, 10]).range([0,100])(0.1234)// 1.234
    d3.scale.linear().domain([0, 10]).rangeRound([0,100])(0.1234)// 1
  • .invert()
     d3.scale.linear().domain([0, 10]).range([0,100]).invert(50); //5
  • .ticks() return uniformly spaced ticks for your axes. (See Axes for examples)
  • .clamp() limit output to range if an input outside the domain is provided

Scales supports various interpolations!


var x = d3.scale.linear()
    .domain([12, 24])
    .range(["steelblue", "brown"]);
x(16); // #666586
x.interpolate(d3.interpolateHsl)(16); //#3cb05f


var x = d3.scale.linear()
    .domain([12, 24])
    .range(["0px", "720px"]);
x(16); // 240px

Other Scales

d3.scale.log(), d3.scale.pow(), d3.scale.quantile()

Ordinal Scales


ordinal.rangePoints(interval[, padding]) – e.g. Plots

ordinal.rangeBands(interval[, padding[, outerPadding]]) - e.g. Bar Chart

Categorical Color Scale


#1f77b4 #ff7f0e #2ca02c #d62728 #9467bd #8c564b #e377c2 #7f7f7f #bcbd22 #17becf

SVG Axes

//Create an axis for a given scale, and configure as desired.
var xAxis = d3.svg.axis()
    .orient("bottom"); // returns a function!

      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis); //rendering axis with call

Need customization!

.axis path, .axis line {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;

See Bar Chart example

## [More SVG Axes](https://github.com/mbostock/d3/wiki/SVG-Axes) [![6186172](http://bl.ocks.org/mbostock/raw/6186172/thumbnail.png)](http://bl.ocks.org/mbostock/6186172) [![5537697](http://bl.ocks.org/mbostock/raw/5537697/thumbnail.png)](http://bl.ocks.org/mbostock/5537697) [![4573883](http://bl.ocks.org/mbostock/raw/4573883/thumbnail.png)](http://bl.ocks.org/mbostock/4573883) [![4403522](http://bl.ocks.org/mbostock/raw/4403522/thumbnail.png)](http://bl.ocks.org/mbostock/4403522) [![4349486](http://bl.ocks.org/mbostock/raw/4349486/thumbnail.png)](http://bl.ocks.org/mbostock/4349486) [![3892919](http://bl.ocks.org/mbostock/raw/3892919/thumbnail.png)](http://bl.ocks.org/mbostock/3892919)
## [More SVG Axes](https://github.com/mbostock/d3/wiki/SVG-Axes) [![3371592](http://bl.ocks.org/mbostock/raw/3371592/thumbnail.png)](http://bl.ocks.org/mbostock/3371592) [![3259783](http://bl.ocks.org/mbostock/raw/3259783/thumbnail.png)](http://bl.ocks.org/mbostock/3259783) [![3212294](http://bl.ocks.org/mbostock/raw/3212294/thumbnail.png)](http://bl.ocks.org/mbostock/3212294) [![2983699](http://bl.ocks.org/mbostock/raw/2983699/thumbnail.png)](http://bl.ocks.org/mbostock/2983699) [![2996766](http://bl.ocks.org/mbostock/raw/2996766/thumbnail.png)](http://bl.ocks.org/mbostock/2996766) [![2996785](http://bl.ocks.org/mbostock/raw/2996785/thumbnail.png)](http://bl.ocks.org/mbostock/2996785) [![1849162](http://bl.ocks.org/mbostock/raw/1849162/thumbnail.png)](http://bl.ocks.org/mbostock/1849162) [![4323929](http://bl.ocks.org/mbostock/raw/4323929/thumbnail.png)](http://bl.ocks.org/mbostock/4323929)

Path Generators & Line Interpolators

Charts from http://bost.ocks.org/mike/d3/workshop/#124

d3.svg.line(), d3.svg.area()

D3 provides helpers to generate SVG lines and areas.

Linear Interpolation

Step Interpolation

Step-before and step-after interpolation are handy for bar charts, and for visualizing step functions (values that change instantaneously rather than gradually).

Basis Interpolation

Note that with basis interpolation, the line doesn’t always go through the control point. D3 also provides cardinal and cubic monotone interpolation; the latter is generally preferred to avoid misleading.

Layouts & Maps


Many layouts are just data generators/modifier.

Source: Chapter 11 in Interactive Data Visualization for the Web by Murray

Force Directed









Load data: d3.csv(), d3.tsv(), d3.json()

Implemented Using XMLHttpRequest

var format = d3.time.format("%b %Y");

d3.csv("stocks.csv", function(d) {
return {
  price: +d.price,  // convert price to number
  date : format.parse(d.date)
}, function(error, rows) {

Note: A web server is required when loading external data. For example with python -m SimpleHTTPServer

Source: http://bost.ocks.org/mike/d3/workshop/#61

Useful Tips

### Useful Helpers * `max()`, `min()`, `range()`, `extent()`, `mean()`, `median()` * `keys()`, `values()` * [Arrays](https://github.com/mbostock/d3/wiki/Arrays) – Learn to use Javascript built-in + D3's [Arrays Helpers](https://github.com/mbostock/d3/wiki/Arrays)! * [SVG Helpers](https://github.com/mbostock/d3/wiki/SVG) e.g. `d3.svg.area()` * Use `window.onresize` event to resize your chart when the window is resized

Reusable d3.

Repeatable, Modifiable, Configurable, Extensible

Need in memory database?

Datavore Crossfilter

Let's Build a Chart!

Use transforms to define a new origin.

It's always a good idea to sketch the transforms before you start.

translate(left,top)origin From http://bost.ocks.org/mike/d3/workshop/#107
Go to the example
### More Examples * https://github.com/mbostock/d3/wiki/Gallery * http://mbostock.github.io/d3/talk/20111018/ * http://bost.ocks.org/mike/map/ * http://christopheviau.com/d3list/gallery.html