D3.js Tutorial

Second Part


by Kanit "Ham" Wongsuphasawat

Interactive Data Lab, University of Washington

@kanitw / kanitw.yellowpigz.com

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

Interactions

Event Listeners

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

See the Pen yziKj by Kanit Wongsuphasawat (@kanitw) on CodePen

See the Pen yziKj by Kanit Wongsuphasawat (@kanitw) on CodePen

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.

See the Pen Dbuhd by Kanit Wongsuphasawat (@kanitw) on CodePen

See the Pen Dbuhd by Kanit Wongsuphasawat (@kanitw) on CodePen

SVG Tooltips

See the Pen mkgqD by Kanit Wongsuphasawat (@kanitw) on CodePen

See the Pen mkgqD by Kanit Wongsuphasawat (@kanitw) on CodePen

HTML Tooltips

See "Div Tooltip HTML" in Murray

Brushing - d3.svg.brush()

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

Scale

Domain ↦ Range

.linear()


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)

Scales supports various interpolator!

Color


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

Size


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

d3.scale.ordinal()

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

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

Categorical Color Scale

.category10()

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

See the Pen zpKuv by Kanit Wongsuphasawat (@kanitw) on CodePen

See the Pen zpKuv by Kanit Wongsuphasawat (@kanitw) on CodePen

http://www.jeromecukier.net/blog/2011/08/11/d3-scales-and-color/

SVG Axes


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

svg.append("g")
      .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)

Layouts & Maps

Pie

Many layouts are just data generators/modifier.

See the Pen IjqLt by Kanit Wongsuphasawat (@kanitw) on CodePen

See the Pen IjqLt by Kanit Wongsuphasawat (@kanitw) on CodePen

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

Force Directed

Pack

Tree

Treemap

Partition

Bundle

Voronoi

Maps

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

d3.csv(), d3.tsv()

Implemented Using XMLHttpRequest


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

d3.csv("stocks.csv", function(stocks) {
  stocks.forEach(function(d) {
    d.price = +d.price;
    d.date = format.parse(d.date);
  });
});
          

Note: A web server is required when loading external data. Use python -m SimpleHTTPServer 8888 is one easy way.

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

See Mike's Simple Area Chart Example

importing data

d3.json()


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

d3.json("stocks.json", function(stocks) {
  stocks.forEach(function(d) {
    d.date = format.parse(d.date);
  });
});
          
Source: http://bost.ocks.org/mike/d3/workshop/#65

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()`

Reusable d3.

Repeatable, Modifiable, Configurable, Extensible

Need in memory database?

Datavore Crossfilter

More Examples

### 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

Q&A

Acknowledgement: This tutorial borrows some contents from Mike Bostock, Vadim Ogievetsky, Scott Murray and Jerome Cukier.