0

I need to make my d3 js chart to be responsive, i.e. scales the chart when user resizes the window. I tried with svg's attributes "viewbox" and "preserveaspectratio" but with no luck. Here is my fiddle

var svg = d3.select("#chart1").append("svg")
    .call(zoom)
    .attr("class", "chart")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom);
    .attr('viewBox','0 0 '+Math.min(pWidth,height)+'       '+Math.min(pWidth,height))
.attr('preserveAspectRatio','xMinYMin');
ksav
  • 20,015
  • 6
  • 46
  • 66
Cayman
  • 367
  • 1
  • 4
  • 16
  • Possible duplicate of [Making D3 responsive: viewBox vs resize()?](https://stackoverflow.com/questions/35773068/making-d3-responsive-viewbox-vs-resize) – ak.leimrey Oct 12 '18 at 09:28
  • As I mentioned I'm aware of "viewbox" solution and tried with it but it looks that I'm doing something wrong and want that somebody guide me how to use it in my scenario. – Cayman Oct 12 '18 at 09:42
  • You might need to listen for a resize event and redraw the entire chart. Look at the answers in the question linked above. – ksav Oct 14 '18 at 09:56

1 Answers1

0

Remove width and height attribute from svg alement.

Add .attr('preserveAspectRatio','xMinYMin'); and .attr("viewBox", '0 0 ' + width + ' ' + height)

Relevant code:

var svg = d3.select("#chart1").append("svg")
.attr("preserveAspectRatio", "xMinYMin meet")
.attr("viewBox", '0 0 ' + width + ' ' + height)
    .call(zoom)
    .attr("class", "chart")
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
Kamil Niski
  • 4,580
  • 1
  • 11
  • 24