The plot below is generated with the D3.js plotting library. Normally, D3.js plots have a fixed size, but we needed responsive plots that automatically adjust their widths and heights depending on the user’s device and screen size. You should see this plot adopt it’s size if you change the width of your browser window.

The Javascript function responsive_d3(svg, aspect_ratio) below turns fixed size plots into responsive plots. The code is an adaptation -with only minor edits- of Brendan Sudol’s code.

function responsive_d3(svg, aspect_ratio) {

  // Get the container width and compute the target height based on the
  // requested aspect ration (width / height)
  var container = d3.select(svg.node().parentNode),
      width = parseInt(container.style("width")),
      height = Math.round(width / aspect_ratio);

  // Bugfix? The container can have something that looks like 4px padding-botton
  // Setting display style flex on the container seems to fix this..
  container.style("display", "flex");

  // add viewBox and preserveAspectRatio properties,
  // and call resize so that svg resizes on inital page load
  svg.attr("viewBox", "0 0 " + width + " " + height)
      .attr("perserveAspectRatio", "xMinYMid")
      .call(resize);

  // to register multiple listeners for same event type,
  // you need to add namespace, i.e., 'click.foo'
  // necessary if you call invoke this function for multiple svgs
  // api docs: https://github.com/mbostock/d3/wiki/Selections#on
  d3.select(window).on("resize." + container.attr("id"), resize);

  // get width of container and resize svg to fit it
  function resize() {
    var targetWidth = parseFloat(container.style("width"));
    svg.attr("width", Math.round(targetWidth));
    svg.attr("height", Math.round(targetWidth / aspect_ratio));
  }

  return [width, height];
}

Example usage:

var svg = d3.select("#plot").append("svg");

var [width, height]  = responsive_d3(svg, 4.0/1.0);

// Add a full width & height rectangle
svg.append("rect")
  .attr("width", width)
  .attr("height", height)
  .style("fill", "#999999");