Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making SVG container 100% width and height of parent container in D3 v4 (instead of by pixels)

Tags:

d3.js

I have a parent container (div.barChartContainer) whose height and width are calculated from the viewport, ex: width: calc(100vh - 200px). The SVG container is appended to the div.barChartContainer element.

I am struggling with how to get the SVG element to be 100% width and height of its parent element, hoping I could get some help. For now I have static pixel amounts (where it currently renders properly, but is non responsive).

Thanks!

  var margin = {top: 20, right: 20, bottom: 30, left: 80},
          width = 960 - margin.left - margin.right,
          height = 500 - margin.top - margin.bottom;          
          // set the ranges
          var y = d3.scaleBand()
          .range([height, 0])
          .padding(0.4);
          var x = d3.scaleLinear()
          .range([0, width]);          
          var svg = d3.select(".barChartContainer").append("svg")
          .attr("width", width + margin.left + margin.right)
          .attr("height", height + margin.top + margin.bottom)
          .append("g")
          .attr("transform",
          "translate(" + margin.left + "," + margin.top + ")");
like image 706
Ron I Avatar asked Jun 29 '17 19:06

Ron I


People also ask

How do I set height and width in SVG?

Any height or width you set for the SVG with CSS will override the height and width attributes on the <svg> . So a rule like svg {width: 100%; height: auto;} will cancel out the dimensions and aspect ratio you set in the code, and give you the default height for inline SVG.

What is d3 SVG?

SVG stands for Scalable Vector Graphics. SVG is an XML-based vector graphics format. It provides options to draw different shapes such as Lines, Rectangles, Circles, Ellipses, etc. Hence, designing visualizations with SVG gives you more power and flexibility.


1 Answers

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")
like image 78
Ron I Avatar answered Sep 16 '22 16:09

Ron I