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 =,
      width = parseInt("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.."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")

  // to register multiple listeners for same event type,
  // you need to add namespace, i.e., ''
  // necessary if you call invoke this function for multiple svgs
  // api docs:"resize." + container.attr("id"), resize);

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

  return [width, height];

Example usage:

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

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

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