score:18

Accepted answer

the solution was to comment out/remove the width and height attribute values and instead add the following two lines:

//- .attr("width", width + margin.left + margin.right)
//- .attr("height", height + margin.top + margin.bottom)
.attr("preserveaspectratio", "xminymin meet")
.attr("viewbox", "0 0 960 500")

score:2

check the svg is drawn with parent height and width.

ref: https://bl.ocks.org/curran/3a68b0c81991e2e94b19

var parentdiv = document.getelementbyid("parentdiv");
var svg = d3.select(parentdiv).append("svg");

function redraw(show) {

  // extract the width and height that was computed by css.
  var width = parentdiv.clientwidth;
  var height = parentdiv.clientheight;
  // use the extracted size to set the size of an svg element.
  svg
    .attr("width", width)
    .attr("height", height);
  if (show === false) {
    svg.style('visibility', 'hidden');
  } else {
    svg.style('visibility', 'visible');
  }

  svg.attr("style", "outline: thin solid red;")
    .append("circle")
    .attr("cx", 30)
    .attr("cy", 30)
    .attr("r", 20);
}

// draw for the first time to initialize.
redraw(false);

// redraw after sometime
settimeout(redraw, 1000);
#parentdiv {
  height: calc(100vh - 100px); /** output container is small for display */ 
  width: calc(100vw - 100px);
  display: block;
  border: 1px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.10/d3.min.js"></script>
<div id="parentdiv"></div>


Related Query