D3.js

Data-Driven Documents

Slides : bit.ly/gdi-d3-slides

Aysegul Yonet / @AysegulYonet

What is D3?

What d3 is not?

Lot's of examples

SVG

  • Another HTML element, except you can not put another HTML element inside an SVG.
  • Does not support common HTML attributes or styles such as position, left, top, right, bottom or float.

Circle




						

Rectangle




						

Line




						

Path




										
						
  • M - move.
  • L - line.
  • z - close path.

Text



	
		Look at me, I am a text.
	

						

Group



	
	
	
	

						

jsFiddle

Other svg Elements



 
  
    
      
    
  
 
  black
  
  red
  
  blue
  
 
						

jsFiddle

SVG attributes

  • background-color ==> fill
  • border ==> stroke
  • More here

Explore

How to D3

Procedure to associate data with DOM

  1. Select a parent container and child nodes
  2. Bind array of data to child nodes
  3. Append nodes to parent container
  4. Bind events, style and animate!

Selection

jQuery


						var paragraphs = $("div p");
					

D3


						var paragraphs = d3.select("div").selectAll("p");
					
jsFiddle

Data

Bind array of data to child nodes


d3.selectAll("p")
	.data([3, 7, 21, 31, 35, 42])
					

JSFiddle

Enter() and Append()


d3.select("body").selectAll("p")
	.data([3, 7, 21, 31, 35, 42])
	.enter().append("p");
					

JSFiddle

Exit() and Remove()


var bars = d3.select('svg').selectAll('rect').data(someData);

//if we have more data, add new rectangles for those data items
bars.enter().append('rect')

//if we have less data points, remove the rectangles that no longer have a data pairing. 
bars.exit().remove();
					

if you forget about the enter and exit selections, you will automatically select only the elements for which there exists corresponding data.


// Update…
var p = d3.select("body").selectAll("p")
	.data([3, 7, 21, 31, 35, 42]);

// Enter…
p.enter().append("p")

// Exit…
p.exit().remove();
					

Chaining


d3.select("body").selectAll("p")
	.data([3, 7, 21, 31, 35, 42])
	.enter().append("p")
	.exit().remove();
					

jsFiddle

Let's give it a try

Exercise: bit.ly/enter-exit-exercise

If you get stuck...Solution

You can operate over the nodes in a declarative way using selector methods.

  • setting attributes or styles
  • registering event listeners
  • adding, removing or sorting nodes
  • and changing HTML or text content

Style

You can use data values or index in a callback to define any property.


d3.select("div").selectAll("p").style("color", function(data, i) {
	return i % 2 ? "red" : "blue";
});
					

JSFiddle

Transition


d3.selectAll("circle")
	.attr("r", "0");
	.transition()
	.duration(750)
	.delay(function(d, i) { return i * 10; })
	.attr("r", function(d) { return Math.sqrt(d); });
					

Try it for yourself

Exercise 0: Look at the example and create a transition to change the size of the circles:bit.ly/d3-transitions

Exercise 1: bit.ly/d3exercise1

In case you get stuck... Solution for Exercise 1

Advanced D3

Scales and Domains

Axis

Loading external data

Scales

Scales transform a number in a certain interval (called the domain) into a number in another interval (called the range).

  • d3.scale.linear - construct a linear quantitative scale.
  • domain - get or set the scale's input domain.
  • range - get or set the scale's output range.

Quantitative Scale

  • Linear scales
  • Logarithmic scales
  • Power scales (including square root scales)

var x = d3.scale.linear()
		.domain([0, d3.max(data)])// your data minimum and maximum
		.range([0, 420]);//the pixels to map to
d3.select(".chart")
	.selectAll("div")
		.data([3, 7, 21, 31, 35, 42])
	.enter().append("div")
		.style("width", function(d) { return x(d) + "px"; })
					
JSFiddle

Ordinal Scale

Ordinal Scale have a discrete domain, such as a set of names or categories.


var x = d3.scale.ordinal()
	.domain(["A", "B", "C", "D", "E", "F"])
	.rangeRoundBands([0, width], .1);
					

Color Categories

d3.scale.category10() - Constructs a new ordinal scale with a range of ten categorical colors:

JSFiddle

Let's refactor our bar chart.

Create a bar charts with scale

Solution: Bar Charts with Scale

Axis

d3.svg.axis creates a new axis generator.

  • axis.scale
  • axis.orient
  • axis.ticks
  • axis.tickFormat

var xAxis = d3.svg.axis()
	.scale(x)
	.orient('bottom')
	.tickValues(data);
					
JSFiddle

d3.time

d3.time.format - creates a new local time formatter for a given specifier.


d3.time.format("%Y-%m-%d");
							
JSFiddle

d3.time.scale - constructs a linear time scale.


var xScale = d3.time.scale()
 .domain([2009-07-13T00:02, 2009-07-13T23:48])
 .rangeRound([0, width]);
 //rangeRound does the same thing as range but rounds the values to integers or begining of dates.
						
JSFiddle

d3.time.intervals - a time interval in local time.

  • d3.time.hour
  • d3.time.week
  • d3.time.monday
  • d3.time.year

Working with Arrays

Most commonly used functions

  • d3.min/d3.max
  • d3.range
  • d3.keys - lists the keys of an associative array.
  • d3.merge - merges multiple arrays into one array.
  • d3.nest - groups array elements hierarchically.

jsFiddle

Loading External Resources

  • d3.json
  • d3.csv
  • d3.tsv

Examples

Bar Chart with tooltip

Pie Chart

Good News!

Other D3 resources

THE END

BY Aysegul Yonet / aysegulyonet@gmail.com