D3 basics

We did a hackathon at work and wanted to do some geographical data visualisation so D3 is the first choice. I mean, that is the name of it D * 3 = Data Driven Documents. I've had limited experience of D3 so I thought it would be a nice foray to it.

The first thing I noticed is that if you have used jQuery before then you are in luck, you have selectors and ajax capabilities. In fact you could probably dispense with jQuery and just use D3.


Selections in D3 are CSS selectors, just like jQuery.

let selector = '#id';
d3.select(selector); //returns the first matching element
d3.selectAll('p'); //returns a node list of all matching elements

The first methods to learn are Enter, which creates placeholder nodes for each data element and returns this as a selection, Update, Exit, and Key.

selection.remove(); //Removes the selection from the DOM
selection.text(); //Sets the text content of the selection 
selection.attr() Set an HTML attribute value on the selection 
d3.selectAll("circle").attr("r", 10)
// set an inline CSS style on the 
selectiond3.selectAll("circle").style("fill", "teal")
// Adds or removes a class from the selection
d3.select("circle").classed("highlight", true)