Working with D3

I find myself picking up and putting down D3 a lot. Each time I pick it up, I relearn the tricks I learnt just before I last put it down. Never again! Here are my tricks for working with D3, written to my future self.

The margin convention

The margin convention makes it easy to distinguish the width and height of the chart area from the width and height of the whole visualisation. As it requires you to use translate, might I also suggest a translate helper function?

A translate helper function

Writing translate is fiddly. A helper function makes it less so:

function translate(x, y) {
return 'translate(' + x + ',' + y + ')';

Now, when you wish to use translate:

g.attr('transform', function (d) { return translate(d.x, d.y); });

A helper function also helps to avoid anonymous functions that span multiple lines.

Anonymous functions that span multiple lines

Once you understand anonymous functions, you’ll want to show off (a possible case of survivorship bias). But anonymous functions that span multiple lines are — like writing translate — fiddly. They’re even more fiddly if you adhere to the “two spaces for a new selection” rule. Try to avoid them, even if that means writing functions that you’ll only use once.

Reusable charts

You start every visualisation thinking about representation, not interaction. By the time you remember that you want to do as well as see, variables are out-of-scope and the update and exit selections are long gone. Make refactoring less painful by writing reusable charts from the start. They’re just closures, after all.

A variable called data

Don’t be tempted.

Single-letter variable names

Be tempted. But use single-letter variable names judiciously. d and i in functions that are called by selections are fine, as they stand for datum and index by convention. g when referring to an SVG group element is also fine, as, well, it’s that in the SVG specification. But did b contain a brush? And did it contain an SVG element brush or a JavaScript function brush? Some Hungarian notation might help, as would not using a single-letter variable name.

Developer tools

You really don’t need to use console.log(d) as much as you think you do. The developer tools in Firefox and Chrome are really rather good.


If you can decide on what messages to pass between views, then you can use d3-dispatch to pass them. When you last put down D3 you were still figuring out some guidelines for how to structure these messages. If you’re picking it up again, then this would be a good place to start.