I've written this chart which is fine, very straightforward but not responsive which it has to be. I've tried a few things no luck. I'm not an expert on d3js.
https://jsfiddle.net/a2zr20ep/14/
I tried the below but it didn't work.
/*window resize operations*/
function resize() {
console.log('----resize function----');
// update width
width = parseInt(d3.select('#chartID').style('width'), 10);
width = width - margin.left - margin.right;
height = parseInt(d3.select("#chartID").style("height"));
height = height - margin.top - margin.bottom;
console.log('----resiz width----'+width);
console.log('----resiz height----'+height);
// resize the chart
xScale.rangeRoundBands([0, width], .1);
yScale.range([height+100, 0]);
yAxis.ticks(Math.max(height/50, 2));
xAxis.ticks(Math.max(width/50, 2));
d3.select(svgContainer.node().parentNode)
.style('width', (width + margin.left + margin.right) + 'px');
svgContainer.selectAll('.g')
.attr("transform", function(d) { return "translate(" + xScale(d.name) + ",0)"; });
svgContainer.selectAll("rect")
.attr("x",function(d) { return d.name; })
.attr("width", xScale.rangeBand());
svgContainer.select('.x.axis').call(xAxis.orient('bottom')).selectAll("text").attr('dy','0.5em').attr('dx','-3em');
}
If you just want to scale your chart, SVG is scalable (vector graphics). It is possible to set a viewBox and a preserveAspectRatio attribute on the SVG element.
If you set these both and apply a with in relative units like %, the SVG just scales with your site without a need to rerender the chart via js.
I actually just pushed a d3 chart template to github where i use this approach.
I forked your fiddle and added the
viewbox
,preserveAspectRatio
and a width of100%
. When you resize the pane, the chart resizes. See this fiddle