Introduction to D3

Matthew Dudak

Presented to BPR Data Board, 19 March 2017

What is D3?

d3 is a Javascript library for producing "data driven documents"

Created my Mike Bostock, formerly of the New York Times

Is D3 a charting library?

No! D3 is a library that can be used to create charts, but it is really a library to bind data to the DOM

Let's get started!

We are going to make a bubble chart

First, create the base html

                  
<head>
  
</head>
<body>
  
</body>
                  
                
This goes in a <script> tag at the end of the body.
                
var graph = d3.select("#graph");
var data = [
  {'x': 10.0, 'y': 30.0, 'r': 10},
  {'x': 50.0, 'y': 10.0, 'r': 5}
];
graph.selectAll("circle")
  .data(data)
  .enter().append("circle")
  .attr("cx", function(d){ return d.x })
  .attr("cy", function(d){ return d.y })
  .attr("r", function(d){ return d.r });
                
              

What?

Let's break it down

The first line just selects the graph element and assigns it to graph so that we can use it later.
                
var graph = d3.select("#graph");
                
              
The second line creates some data object.
                
var data = [
  {'x': 10.0, 'y': 30.0, 'r': 10},
  {'x': 50.0, 'y': 10.0, 'r': 5}
];
                
              
Okay, here is the interesting part, we start by selecting all circle elements in the SVG.
                
graph.selectAll("circle")
                
              

This is really weird

The SVG doesn't have any circles in it.

"Instead of telling D3 how to do something, tell D3 what you want." - Mike Bostock

So, we are telling D3 we want there to be circles

Once we've told D3 that we want there to be circles, we bind data to the circles
                
graph.selectAll("circle")
  .data(data)
                
              
This is very important, and probably the most important thing that D3 does
Now we enter the circles that we want to create and actually add them to the svg.
                
graph.selectAll("circle")
  .data(data)
  .enter().append("circle")
                
              
Finally, we change the attributes of those circles, based on the data
                
graph.selectAll("circle")
  .data(data)
  .enter().append("circle")
  .attr("cx", function(d){ return d.x })
  .attr("cy", function(d){ return d.y })
  .attr("r", function(d){ return d.r });
                
              

This is our result:

An aside:

Something that's key to remember is that SVG coordinates are not the same as they are in a graph. Instead of starting in the lower left, they start in the upper left. Keep this in mind going forward.

Okay, but that's kind of boring. Let's make a graph!

We want our graph to look like this:

We will use a bit different of a setup here.
                
<head>


</head>
<body>
</body>
                
              
Cut out the pre-created svg element, and add in some style.
Now, let's start the Javascript.
                
var margin = {
    top: 20,
    right: 10,
    bottom: 45,
    left: 40
};
var frameWidth = 960;
    frameHeight = 500;
var width = frameWidth - margin.left - margin.right,
    height = frameHeight - margin.top - margin.bottom;
var graph = d3.select("body").append("svg")
    .attr("width", frameWidth)
    .attr("height", frameHeight)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
                
              
All of this is just to set up the graph element. See here for more details.
Create x, y, and r linear scales. These will be used to map from the data to the svg coordinates.
                
var x = d3.scale.linear()
    .range([0, width]);
var y = d3.scale.linear()
    .range([height, 0]);
var r = d3.scale.linear()
    .range([.05, 30]);
                
              
Turn these scales into axes on the graphs (D3 makes the svg path for you)
                
var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom");
var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left");
                
              
Here's what the data looks like:
                
Name,IA Diff,NH Diff,Party,IA Result
Santorum-2012,7.60,8.00,Republican,24.6
Romney-2012,2.50,-0.33,Republican,24.5
Paul-2012,0.07,1.33,Republican,21.4
Gingrich-2012,-0.70,-4.67,Republican,13.3
Perry-2012,-0.03,-1.67,Republican,10.3
Bachmann-2012,-2.00,-4.57,Republican,5
Hunstman-2012,-2.07,-3.00,Republican,0.6
                
              
Read in the data
                
d3.csv("data.csv", function(error, data) {})
                
              
The d3.csv() function is an asynchronous function so we have the use a callback function which is executed when the data is read in.
Let's flesh out the function. First, tell it what to do in the case of an error.
                
if (error) throw error;
                
              
Include a loop which types all of the relevant columns to numbers.
                
data.forEach(function(d) {
  d['IA Diff'] = +d['IA Diff'];
  d['NH Diff'] = +d['NH Diff'];
  d['IA Result'] = +d['IA Result'];
})
                
              
Now that we have our data read in, we can set the domains of x, y, and r.
                
x.domain(d3.extent(data, function(d) {
    return d['IA Diff']
})).nice();
y.domain(d3.extent(data, function(d) {
    return d['NH Diff']
})).nice();
r.domain(d3.extent(data, function(d) { return Math.sqrt(d['IA Result']) })).nice();
                
              
The .nice() at the end just makes it round, and we take the square root for r so that the circles are sized proportionally to the area, not the radius (but the radius is the parameter we control).
Now, we add the x-axis onto the svg.
                
graph.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + y(0) + ")")
    .call(xAxis)
                
              
Since some data points in this graph have a negative y value, we set the x-axis to be wherever the y=0 point is (thus the translate transform)
We can also continue the x-axis chain from the previous slide and add a text label.
                
.append("text")
  .attr("class", "label")
  .attr("x", width)
  .attr("y", 40)
  .style("text-anchor", "end")
  .text("Iowa Polling-Vote Difference");
                
              
                
graph.append("g")
    .attr("class", "y axis")
    .attr("transform", "translate(" + x(0) + ",0)")
    .call(yAxis)
  .append("text")
    .attr("transform", "rotate(-90)")
    .attr("class", "label")
    .attr("y", -40)
    .attr("x", 0)
    .style("text-anchor", "end")
    .text("NH Polling-Vote Difference");
                
              
The main difference here is the .attr("transform", "rotate(-90)") which is there just so that the text is rotated.
And finally, we are ready to add all of our points. This works basically the same as making the circles before. We start by adding the selecting all, adding the data, entering and appending.
                
graph.selectAll(".dot")
  .data(data)
  .enter().append("circle")
  .attr("class", "dot")
                
              
These lines set the radius and position. Instead of using the numbers from the data directly like we did before, we now use the x, y, and r scales.
                
.attr("r", function(d) { return r(Math.sqrt(d['IA Result'])) })
.attr("cx", function(d) { return x(d['IA Diff']) })
.attr("cy", function(d){ return y(d['NH Diff']) })
                
              
And finally we add some styling.
                
.style("fill", "#a034cc")
.style("fill-opacity", "0.4")
                
              
That's it!
Check out the code here: https://github.com/Brown-Political-Review/d3-tutorial