Reusable Charting with D3

I love the D3js framework, however it’s not initially intuitive how to create charts that have reusable components. After working extensively with this framework over the last few months, I’ve found a good way to introduce a little more extensibility into the default approach.

For the following examples we use ES6 features, along with flexbox for positioning, which means that it might not work on all browsers. In production, I would recommend transpiling to ES5 for compatibility.

Motivation

D3 does not inherently provide many tools to help developers create reusable charts. Often times documentation can be sparse on library features, and most code examples are obtuse and hard to follow (or use) unless you’re an expert in the framework.

The goal of this extension is to allow for more use and reuse of these charts.

The core framework

There’s a lot of code here that at first glance doesn’t seem that related to D3, but skim through and I’ll explain below.

In short this attempts to provide a universal superclass for all charts created with D3. This allows us to solve universal problems (or even common problems) only once, include the solution in this superclass, and never have to solve the same problem again. For instance, this initial superclass adds the following features to any plot initialized with it

  • Margins
  • Easy-to-initialize elements

Basic Demonstration

Using this framework we can plot a simple resizing rectangle.

With corresponding code,

Something more complicated

Showing more power of this approach, we can create a simple margin demonstration

With corresponding code,

So what?

If you’re creating a ton of D3 plots, I highly recommend tinkering with plot creation using an approach like this. It’s saved me a ton of time, and helped improve every part of working with D3.

Feel free to download and play with the code at https://www.dataleek.io/js/ex.js



Leave a Reply

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