# Fun with Circles in D3

- Link: https://cagrimmett.com/2016/08/16/d3-fun-with-circles/
- Published: 2016-08-16T04:00:00-04:00
- Author: Chuck Grimmett

These are my outputs from [Mike Bostock’s Three Little Circles Tutorial](https://bost.ocks.org/mike/circles/),
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:

    ```html
     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!

    ```javascript
    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?

    ```javascript
    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?

    ```javascript
    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.

    ```javascript
    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.
