Drawing Some Charts With D3

I have to admit, I was pretty intimidated by learning D3. This is the second part of the FreeCodeCamp data visualization section, the first part being React. After all the trouble I had learning React (or more to the point, finding anything current to learn React) I was dreading starting D3. As it turns out D3 is pretty simple, once you get the hang of the basics.

The Basics

I was surprised to find that D3 is a lot like (shudder) jQuery in syntax. Most methods return an object – allowing method chaining – which greatly simplifies the entire process. Once I started thinking of D3 in these terms the projects practically coded themselves.

The only other learning curve seems to be getting comfortable with svgs, which fortunately I have used in previous projects so there wasn’t much new there. In fact, I think most of the code I wrote for my D3 projects was to handle svgs and relatively little pertained to D3 or the data being used.

In a nutshell, D3 takes a whole lot of data and turns it into pictures. This is probably a great over-simplification which would likely irritate Mike Bostock (creator of D3), and really doesn’t do it justice, but there you go. Data to pictures.

Let’s Look At Some Code

This comes from a great, if outdated tutorial by Scott Murray written in the time of D3 v3, but all of this code will work in v4

First up, using D3 to add an SVG element to our page

const w = 500;
const h = 100;
const barPadding = 1; 

const svg = d3.select("body")
              .attr("width", w)
              .attr("height", h);

SVGs have default width and height attributes, so you do not necessarily have to specify these values, but I can’t imagine that the defaults will always be the size you’re after. So it’s good practice to specify these values.

D3 will loop through all provided data once it’s bound, applying your logic to each item in your dataset. That happens here:

   .attr("x", (d, i) => {
     return i * (w / dataset.length);
   .attr("y", (d) => {
     return h - d * 4;
   .attr("width", w / dataset.length - barPadding)
   .attr("height", (d) => {
     return d * 4;
   .attr("fill", (d) => {
     return "rgb(0, 0, " + (d * 10) + ")";

I’ll leave it to you to read through Scott Murray’s tutorial to see what’s going on here. You can view the final results of this code here.

To Wrap This Up

D3 is different, but not scary. It’s powerful, but not difficult. Getting a simple chart onto the screen takes very little effort and the learning curve is not at all steep. Fear not the D3.