Responsive d3.js

OCTOBER 14, 2013

It's increasingly important to make d3.js charts responsive for touch-based devices such as mobile and tablet. While this approach doesn't solve everything, it's one way of making SVG based charts dynamic and responsive.

UPDATE  You can also check responsive and interactive maps with d3.js in this post.

As this site uses Bootstrap 3, the layout is very responsive and mobile first design. So, when it comes to drawing d3.js charts, it's ideal to leverage that. If you have complex chart drawings, you don't want to deal with every element's width and height. Instead, you should set a viewBox attribute in SVG element. Then you just need to dynamically change SVG's width and height, as the parent container gets resized.

var width = $(".map").width(),
    aspect = 500 / 950;
var svg =".map").append("svg")
    .attr("preserveAspectRatio", "xMidYMid")
    .attr("viewBox", "0 0 950 500")
    .attr("width", width)
    .attr("height", width * aspect);
$(window).resize(function() {
  var width = $(".map").width();
  svg.attr("width", width);
  svg.attr("height", width * aspect);

Here is the responsive d3.js-based SVG map. Original code was taken from the d3.js example. If you are on desktop, you can see responsiveness by resizing the browser window. If you are on mobile/tablet, try rotating the device and change orientations.

Of course, there are many cases where one chart type cannot satisfy all form factors. In those cases, you might want to completely swap charts to match that form factor, instead of resizing it.

Related Posts

SVG-based Sparkline with d3.js

This is a tutorial of how to create various SVG based sparklines with d3.js. Sparkline, a tiny line chart, is often very effective and visually appealing, especially for today's small screen devices.

Interactive Map with d3.js

This is a step by step tutorial of how to make responsive, interactive and zoomable map with d3.js. Converting Shapefile into GeoJSON then Topojson, you can build web/mobile-ready map application.

Blurring UIView in iOS7

In iOS7, screen blurring is everywhere. Fortunately, they opened the API so that you can also implement it very easily.