Graphs 'n stuff: simple scatterplot with d3

Recently I’ve been learning how to use d3.js (D3), often touted as an incredibly powerful cool for creating graphics. I thought it’d be helpful to any other novices out there to write up my D3 examples as I do them. I come from a statistical background and while I have plenty of experience coding in R, JavaScript is a whole new challenge.

I’ll be writing up short explanations on any particular aspect that confuses me with a particular visualisation. Hopefully this can save someone else a few minutes of their day.

Let’s get started!

Below is a simple scatter plot. This particular graph plots the runtime of a randomforest as a function of the number of observations of the sample. Today, however, it’s just a simple dataset!

The scatterplot is very basic. It consists of an x-axis and a y-axis, and labels for these axes. It consists of black dots to represent data. It also consists of an exceedingly basic tooltip function: you can mouseover each datapoint to see its x and y values.

The dataset contains 50 observations and  is located in a file called “obs_timings.csv”. Whilst we’ll be putting “Number of Rows” as our label on the graph, here I’ve just labelled the x-values as"size" to save my tired hands.

An excerpt of the dataset looks like


The code is listed below:

<!DOCTYPE html>
<meta charset="utf-8">
		.axis path,
		.axis line  
			fill: none;
			stroke: black;
			shape-rendering: crispEdges;
		.axis text 
			font-family: sans-serif;
			font-size: 11px;
			position: absolute;           
			text-align: center;           
			width: 70px;                  
			height: 14px;                 
			padding: 2px;             
			font: 12px sans-serif;        
			background: lightsteelblue;   
			border: 0px;      
			border-radius: 8px;           
			pointer-events: none;         
<script src=""> </script> 
	var max_time = 22
	var margin = {top: 20, right: 20, bottom: 30, left: 40},
	width = 960 - margin.left - margin.right,
	height = 500 - - margin.bottom;
	//Create a svg element to store the graph in 
	var svg ="body").append("svg")
		.attr("width" , width + margin.left + margin.right)
		.attr("height" , height + + margin.bottom)
		.attr("transform", "translate(" + margin.left + "," + + ")");
	//Set up scales that we can use to draw the axes
	var x = d3.scale.linear()
	var y = d3.scale.linear()
		.domain([0,max_time + 1])
	//Setting up the axes
	var xAxis = d3.svg.axis()
	var yAxis = d3.svg.axis()
	//Add the axis to our svg element
	// x-axis
	.attr("class", "x axis label")
	.attr("transform", "translate(" + 0 + "," + height + ")")
	.text("number of rows")
	.attr("x", width)
	.attr("y", -6)
	.style("text-anchor", "end");	
	// y-axis
	.attr("class", "y axis label")
	.attr("transform", "rotate(-90)")
	.attr("dy", ".71em") 
	//For the mouseover bubbles
	var tooltip ="body")

	var datas; 	
	d3.csv("obs_timings.csv", function(d) 
				time : +d.time,
				size : +d.size
			datas = data; 
			.attr("cx", function(d) {return x(d.size); })
			.attr("cy", function(d) {return y(d.time); })
			.attr("r", 5)
			.on("mouseover", function(d)
					.style("opacity", .9);
				tooltip.html("(" + d3.round(d.size) + "," + d3.round(d.time,2) + ")") //what to display on mouseover
				.style("left", (d3.event.pageX + 5) + "px")
				.style("top", (d3.event.pageY - 28) + "px")
				.style("display", "block")
			.on("mouseout", function(d) 

A few things that tripped me up:

  • I found the d3.csv function really confusing at first. According to the d3.js documentation, this function looks like: d3.csv(url[, accessor][, callback]). Not knowing what either an accessor function or a callback function does with any great clarity, it was no wonder that I run into problems with the scope of the function.It turns out that code for generating the graph should be written inside the d3.csv function, as a callback function. If I try to access it outside the function, my code will return errors and behave strangely. I found that I could execute my commands in the javascript console and everything would work perfectly, but when I ran it as a single script, it wouldn’t work. The reason for this? Javascript runs asynchronously. That’s where callback functions come into play - functions that get invoked once the data is loaded. Otherwise, you’re trying to work with data that hasn’t been loaded and parsed, and that’s not going to end romantically.
  • SVG’s x and y attributes are absolute coordinates, while dx and dy are relative coordinates, with respect to the specified x and y. This appears often in code that looks somewhat like
    .text("My text")
    .attr("x",function (d) {return d;})
    .attr("transform", function(d, i) {return "rotate("+45*i+","+d+",200)";});

When dy is used together with em (scalable font size units) like .attr("dy","0.35em") , it aligns text relative to the specified y coordinate. The scalable font units allow the positioning of the text to be dependent on the size of the text. Here, .35 em has the effect of vertically centering the text by adding half the height of the text to the y dimension. This could have many uses, and a common one is axis labels.