D3.js tutorial - Part 11 - Responsive chart


In part 8 of this tutorial, we created a simple bar chart with fixed size (200 x 100 pixels).

We now want this chart to become responsive, i.e. the chart size will adapt automaticaly if the size of the parent division changes, for example when the window is resized.

A commonly used solution is the handle the resize event to recalculate the chart properties. It works, but it's not the best alternative.

The best option is to add the attribute preserveAspectRatio to the SVG container. As mentionned in the documentaiton "The preserveAspectRatio attribute indicates how an element with a viewBox providing a given aspect ratio must fit into a viewport with a different aspect ratio. ".

The documentation also mentions "Because the aspect ratio of an SVG image is defined by the viewBox attribute, if this attribute isn't set, the preserveAspectRatio attribute has no effect".

Responsive bar chart

Let's create a viewport in our SVG container and add the preserveAspectRatio attribute:

// Create our SVG container with grey background
var svg = d3.select("#bar-chart")
            .attr('viewBox','0 0 200 100' )

Here is probably the simplest bar chart you can create with D3.js:

See also

Last update : 01/29/2020