D3.js

D3

D3 very popular way to do data visualization.

D3 is very popular on the web. It’s great for storytelling. It’s great for interactivity; to have rich tooltips, dynamic plotting, user interaction.

Very steep learning curve; need to learn some javascript, html, and css. Starting requires patience and tolerance for confusion.

D3 was started as Protovis in Stanford by Mike Bostock and Jeff Heer.

D3 is a really powerful for-loop with a ton of useful helper functions; does a lot of things automatically.

Declarative, domain-specific language for manipulationg the DOM.

Steps to D3

1) Create empty project folder

2) Download latest version of D3 (see [https://d3js.org]). Place inside that folder and unzip.

3) Create an empty HTML page named index.html. HTML is just plain text so you can write in an text editor, I personally use Atom

The majority of the time you can view local HTML files directly in your web browser. Sometimes it won’t work as the browser may prevent JavaScript for security reasons (computers don’t allow browser to read your documents). To be more reliable, you could set up your own local web server. An easy way to set up a Local Web Server is via python with “python -m http.server 8000”.

It’s always good practice to use a web browser like Chrome and use the developer tools including Right Clicking and choosing Select.

You define a template for each element, D3 draws one element for each data point.

JavaScipt

  • All variables are global, unless declared using var.
  • Semicolons are optional
  • JS arrays and objects are almost exactly the same syntax as python lists and dicts.
  • object.key is the same as object[‘key’]
  • print to console using console.log()
  • JavaScript functions are objectives themselves; they can be stored as variables and passed as parameters.

  • numbers = [25,36,49] // define array
  • numbers.map(Math.sqrt(numbers)) // gives a new array of all the square roots

SVG

SVG stands for Scalable Vector Graphics. It means that graphs can keep resolution even at large zooms. This does not happen with Raster images like .png or .jpg. It is actually an XML document.

Origin

The origin is the top left!

Steps

1) Select - you have to select the canvas (usually a div) 2) Append - add something to the canvas (add an svg) 3) Add Elements - .append(cricle)

Grouping

g is a generic container group element. You can apply transformations or color of the entire group. You append a group till the canvas then can append whatever to the group. Group.append(“circle”)

Writing Chained Code

Here’s an example of some code via chains:

d3 - references the D3 object.

.select(“body”) - takes in a CSS selector as input and returns a reference to the first element in the document that matches.

.append(“p”) - adds a new element in our document and throws it inside the end of whatever was selected.

.txt(“This is a paragraph”) - inserts a string into the opening and closing tags of the selection.

That same code is rewritten without chains as:

var body = d3.select(“body”);

var p = body.append(“p”);

p.text(“Hello this is my paragraph”);

Getting Data in

Written Arrays

You can always just create an array such as:

’'’javascript var dataset = [5,10,15,20,25] ‘’’

But more than likely you’ll have a JSON or csv.

CSV’s

CSV’s can be read in such as:

’'’javascript d3.csv(“food.csv”, function(data) { console.log(data); }); ‘’’

This takes in a path to the csv and an anonymous function called a callback function. That is, the function is only called after the csv has been loaded into memory. In this case, the data is just being logged.

D3 defaults to loading in everything as a string. You could create a function to make sure the variables are read the way you want them to. You can loop through all the numbers and suggest the type is number by +d.value. Or you can use a parse function below:

’'’javascript var rowConverter = function(d) { return { Food: d.Food, //No conversion Deliciousness: parseFloat(d.Deliciousness) }; }

d3.csv(“food.csv”, rowConverter, function(data) { console.log(data); });

’’’

d3.csv(fileloc,callback)

d3.tsv(fileloc,callback)

d3.json(fileloc,callback)

JSON

JSON seems to be very popular in D3. It isn’t dissimilar to the csv function.

’'’javascript d3.json(“waterfallVelocities.json”, function(json) { console.log(json); //Log output to console });

’’’

Using that data

In order to use that data, it has to be associated with an element in the document that is already created.

If you wanted to create paragraphs with each value from a csv you could write:

’'’javascript d3.select(“body”).selectAll(“p”) .data(dataset) .enter() .append(“p”) .text(function(d) { return d; });

’’’

Functions / Methods

Methods or functions are the same thing, different words. They bring in an input and give an output.

They usually follow a format like this:

‘‘‘javascript function(input_value) { //Calculate something here return output_value; } ‘‘‘

Anonymous functions don’t have name vs you can have a named funtion:

‘javascript var doSomething = function() { //Code to do something here ‘

Drawing

.attr() sets the document attribute values. It sets HTML attributes. you can do something like .attr(“class”,”bar”)

style() applies CSS styles directly to an element

Importing D3

You always have to important it within the head. Always state the charset is unicode (utf-8)

Learn D3

Scott Murray’s Interactive Data Visualization for the Web

Refer to the API Reference OFTEN

Interactions

use .on(“click”) and update something

Animations in D3

Transitions are pretty useful. You just need to state the new height and the delay and the duration and D3 takes care of the rest.

This medium article is good

Moving thousands of dots

Animated Bubble Chart

Amelia Watternberger

D3 To WordPress

Add D3 Charts