Fun with Circles in D3

These are my outputs from Mike Bostock’s Three Little Circles Tutorial, slightly modified so I could understand how each of these items work. This is a tutorial about selections and basic data joins.

We start with three basic SVG circles:

 height="50px" width="250px">    cx="40" cy="20" r="10">    cx="80" cy="20" r="10">    cx="120" cy="20" r="10"> 

Now let’s select them and make them a little bigger and orange!

var circle = d3.selectAll("svg#orange circle") 	.style("fill", "darkorange") 	.attr("r", 20);

Now how about making them light blue and having a randomly-generated height that resets every second?

function jump(){ var circle = d3.selectAll("svg#random-height circle") 	.style("fill", "lightblue") 	.attr("cy", function() { return Math.random() * 150 + 10;}); } jump(); setInterval(jump, 1000);

That’s cool!

Now let’s do some data joins. How about making the radius of the circle a function of a data set?

var circle = d3.selectAll("svg#data-radius circle") 	.data([2, 3, 4]) 	.attr("r", function(d){ return d*d; });

Looks like the radius is a square of the data. Go ahead and inspect the element to confirm!

You’ll notice that the function uses the name d to refer to bound data.

Let’t make these purple for variety and write a linear function to space them out horizontally.

var circle = d3.selectAll("svg#data-cx circle") 	.style("fill","purple") 	.data([2, 3, 4]) 	.attr("cx", function(d,i){ return i*100 + 70});

This uses a new function: The index of the element within its selection. The index is often useful for positioning elements sequentially. We call it i by convention.

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: