Well, hello!

D3.js is a data visualization library for the web. D3 stands for Data-Driven Documents. It makes use of SVG to quickly and beautifully render JSON or CSV data. This is a very basic introduction into D3. There's much more out in the world. So, hopefully, this just wets your appetite for D3. Most of the data visualization you see on the web is probably written in D3.

D3 Show Reel from Mike Bostock on Vimeo.

That was a little intro to D3 from one of its creators, Mike Bostock.

You can do really cool stuff with D3. We're just not there yet....

SVG

SVG stands for Scalable Vector Graphics. It's basically a 2D graphics format described in an XML format. When HTML5 came around, SVG could be directly used in web browsers. The benefit to SVG is you can resize them to any size, and you don't lose any of those crisp edges, that you would get with say, a .jpeg. Sample SVG.

The Nit and the Grit

D3 requires you know HTML, CSS, Javascript fairly well, and it has a pretty steep learning curve. I'm still learning, too! I'm not super-D3-hero-expert yet, but I can give you a basic intro. D3 isn't just charts. It's not a charting library. There's no 'barchart()' function. You have to generate rectangles from your data, to make a bar chart. It can do lots of things, probably things we can't even imagine. It can be simply described as bring data to life. Oh, and it doesn't work with older, crappy browsers.

Doc and Examples

There's lots of great documentation on how to use D3, but one of the best ways to learn is through examples. Of course, the D3 home page is one of your best resources, but one of the greatest troves of D3 examples lives under one its creators, the the aforementioned Mike Bostock. Check it out. Seriously.

Get started

Things you need.

In the examples I show here, I'll just keep it simple, but if you have more complex data, you'll want to serve it up in an external JSON or CSV file, or you'll want to call some sort of web service. You can do that locally with Python, Node or if you're building a Java app, you'll probably already have a Tomcat/Jetty server and aren't too concerned about this step. WebStorm does that for you, so it's super handy.

Selections

Selections get you access to elements in the DOM, so D3 can do stuff to them. You can think of them similar to jQuery selectors, and they look something like:

                
                 d3.select('#select-first'); // element with id select-first
                 d3.selectAll('p'); // selects all paragraphs
                 d3.selectAll('.banana'); // select all elements with class banana
                 
            

Like a lot of js libraries, D3 uses chaining. It's super convenient when you're making lots of changes to elements (like you will in D3).

                
                    var circ = d3.select('#select-first'); // element with id select-first

                    circ.attr("fill", "red") // make the fill red
                        .attr("r", 10) // make the radius 10
                        .attr("stroke", "black") // make it black stroke
                        .attr("stroke-width", 2); // make the stroke width 2 and end the statment
                
            

Usually, you want to add new stuff using D3, for that, use append()

                
                    var p = d3.select('#add-stuff-here'); // element with id add-stuff-here

                    p.append('svg') // add the svg element
                        .attr('width', 500)
                        .attr('height', 40)
                    .append('circle')
                        .attr('fill', 'blue') // the fill
                        .attr('r', 10) // radius
                        .attr('cx', 50) // center x-coordinate
                        .attr('cy', 20); // center y-coordinate
                
            

Data-Joins

The stuff D3 is made of. You need the data, right? Of course, my horse! This is how you bind data to the DOM to create elements. You do this with the datum() for a single svg element or data() for a group of svg elements.

                
                    var div = d3.select('#data-binds-here'); // element with id data-binds-here

                    var svg = div.append('svg') // add the svg element
                    .attr('width', 200)
                    .attr('height', 200)

                    var circ = svg.append('circle')
                    .attr('fill', 'green') // fill
                    .attr('cx', 100) // center x-coordinate
                    .attr('cy', 100); // center y-coordinate

                    circ.datum(40); // set datum

                    // bind the radius to the datum using an anonymous function with variable d
                    circ.attr('r', function(d) { return d; });
                
            

Create a simple bar chart

Ahhhhhh! The stuff of dreams. This is the real D3 deal!

                
                    // create a bar chart based on this population data
                    var popData = [
                        {age:"80 and up", value:1.6, position:0},
                        {age:"75 - 79", value:1.5, position:1},
                        {age:"70 - 74", value:2.1, position:2},
                        {age:"65 - 69", value:2.6, position:3},
                        {age:"60 - 64", value:3.4, position:4},
                        {age:"55 - 59", value:4.5, position:5},
                        {age:"50 - 54", value:5.1, position:6},
                        {age:"45 - 49", value:6.0, position:7},
                        {age:"40 - 44", value:6.6, position:8},
                        {age:"35 - 39", value:7.1, position:9},
                        {age:"30 - 34", value:7.3, position:10},
                        {age:"25 - 29", value:8.1, position:11},
                        {age:"20 - 24", value:8.9, position:12},
                        {age:"15 - 19", value:8.8, position:13},
                        {age:"10 - 14", value:8.6, position:14},
                        {age:"5 - 9", value:8.8, position:15},
                        {age:"0 - 4", value:9.3, position:16}
                    ];

                    // log it
                    console.log(popData);

                    // create the svg
                    var svg = d3.select("#bar-chart-lives-here")
                        .append("svg");
                    var barGroup = svg.append("g")  // "g" are svg elements bound together
                        .attr("class", "bar")
                        .attr("fill", "white");

                    barGroup.selectAll("rect")
                        .data(popData)
                    .enter() // creates a new data node for each data point
                        .append("rect")
                        .attr("fill", "orange")
                        .attr("x", 0)
                        .attr("y", function(d, i) {
                            // d = popData
                            // i = the current index
                            return i * 25;
                        })
                        .attr('height', '20px')
                        .attr('width', function(d) {
                            // just use our data point
                            return d.value * 100;
                        })
                        .append("svg:title") // creates a tooltip
                        .text(function(d) { return d.value; });

                
            

That's pretty cool. Wouldn't it be create if it had labels?

                
                    // create vars to make life easy
                    var barHeight = 20;
                    var barGap = 5;
                    var barSpacing = barHeight + barGap;

                    // create a group for our text
                    var barLabelGroup = svg.append("g");

                    barLabelGroup.selectAll("text")
                        .data(popData)
                        .enter().append("text")
                        .attr("x",3)
                         .attr("y", function(d, i) {return (i) * barSpacing + barHeight*(2/3)})
                        .text(function(d) {return d.age});
                
            

Fin

So, that's a small taste of D3. I'll wrap it up with some links, so you can continue to explore D3.