Establishing Reusable Code

Zoë Farmer

Made with ES6, D3, Jupyter, Reveal.js

Who am I

What’s the problem?

TL;DR – D3 doesn’t lend itself to reuse

Example - Scatterplot

png

And the code?

http://bl.ocks.org/weiglemc/6185069

So what can we do?

Use Classes

class Chart {
    constructor(selector, params={}) {
        this.selector = selector;
        this.svg = d3.select(selector).append('svg');
        this.chart = this.svg.append('g').classed('chart', true);
        this.params = params; 
    }
    newGroup(name) {
        if (this[name]) { this[name].remove() }
        this[name] = this.chart.append('g').classed(name, true);
    }
}
class Bar extends Chart { ... }

Separate Interaction

Write with reuse in mind

class Bar extends Chart {
...
    drawBars(data) {
        this.newGroup('bars');
        this.bars
            .selectAll('rect')
            .data(data)
            .enter()
            .append('rect')
            .attr('transform', d => `translate(${this.xScale(d.key)})`)
            .attr('width', this.xScale.bandwidth())
            .attr('height', d => this.yScale(d.value))
            .attr('fill', d => d.properties.fill)....
    }
...
}

Takehome

It’s more work up front for each chart, but it will pay dividends.

Questions?

Buy me a beer, or bug me at