A Simple Responsive D3.js Example

I’ve a growing number of people asking me about responsive data visualisation particularly how this can be implemented using D3. Therefore this article describes a simple architecture for making D3 visualisations responsive.

In this example we have a bar chart that will respond to changes in the viewport width. (Try resizing your browser window to see this bar chart resize.)


When the viewport size changes the following will happen:

  • update the range of the x-scale
  • update the x-axis
  • update the bars

Note that we’re using an ordinal scale with range-bands for the x positions of the bars which saves us a bit of work.

Resize event

Let’s start by writing the resize event handler:

function update() {
  updateScales();
  updateAxes();
  updateBars();
}

W.addListener(update);

Note we’re using a great little library called W which handles common tasks related to window resizing.

Update functions

We’ve divided the update into three functions: updateScales, updateAxes and updateBars.

The first updates our scale function’s range according to the new viewport width. (Note that we use d3.min to ensure that the width doesn’t exceed maxWidth.)

function updateScales() {
  var width = d3.min([W.getViewportWidth(), maxWidth]) - rightPadding;
  xScale.rangeBands([0, width], 0.04);
}


Next is the function to update the x-axis:

function updateAxes() {
  d3.select('.x.axis').call(xAxisComponent);
}


Finally, updateBars handles the updating of the bar geometry. This uses a simlar pattern to Mike Bostock’s General Update Pattern.

function updateBars() {
  // Perform the data join
  var u = d3.selectAll('rect')
    .data(data);

  // Add bars
  u.enter()
    .append('rect');

  // Remove bars
  u.exit()
    .remove();

  // Update bar position, width & height
  u.attr('x', function(d, i) {return xScale(i);})
    .attr('width', xScale.rangeBand())
    .attr('y', function(d) {return yScale(d);})
    .attr('height', function(d) {return yScale(0) - yScale(d);});
}

View the sourcecode

Summary

This is a barebones demonstration of responsive D3 code and hopefully gives a bit of insight into how you might go about making your own D3 chart responsive.

I think it’s also worth saying that when making a data visualisation responsive, the design must be considered carefully. In this example we can just about get away with squashing the bars up on smaller screens. However, if there were more bars we might want to think about orienting them horizontally.

Stay in touch

I’d love to keep you informed of new articles and other news so if you’re interested please add your name to my mailing list and I’ll keep you updated.