0

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'); 
}
Paweł Obrok
  • 22,568
  • 8
  • 74
  • 70
  • See [this question](https://stackoverflow.com/questions/9400615/whats-the-best-way-to-make-a-d3-js-visualisation-layout-responsive). – Lars Kotthoff Jun 08 '15 at 02:21

1 Answers1

0

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 of 100%. When you resize the pane, the chart resizes. See this fiddle

jhinzmann
  • 968
  • 6
  • 15
  • Hi there, your jsfiddle was good and thank you so much, I'm not an expert at d3js, but your solution I will study and learn from as d3 is the way to go. d3js has to promote ALL their charts for responsiveness now or else they're toast - again a big thanks for my pestering. Andy – TravelAndy Jun 08 '15 at 22:03
  • Glad that i could help you ;) if my answer solved your problem, please mark it as accepted answer. That way it is clear that your question was solved and others can see which answer solved your problem – jhinzmann Jun 08 '15 at 22:13