responsive D3 chart

You can make the chart resize using a combination of viewBox and preserveAspectRatio attributes on the SVG element.

See this jsfiddle for the full example: http://jsfiddle.net/BTfmH/12/

var svg = d3.select('.chart-container').append("svg")
    .attr("width", '100%')
    .attr("height", '100%')
    .attr('viewBox','0 0 '+Math.min(width,height)+' '+Math.min(width,height))
    .attr('preserveAspectRatio','xMinYMin')
    .append("g")
    .attr("transform", "translate(" + Math.min(width,height) / 2 + "," + Math.min(width,height) / 2 + ")");

You won’t even need a resize handler with this method.

Leave a Comment