窗口D3图表的跨度宽度

时间:2018-01-18 08:03:13

标签: javascript css d3.js

如何让以下图表与浏览器左侧的线条齐平。它似乎一直向右,但我希望它跨越窗口的整个宽度。对于宽度I' m使用width = window.innerWidth但似乎没有做我想的那样。您可以在此处查看图表(https://bl.ocks.org/centem/ede5bb7d11fb80c82ad9a221c5a2b7ee

1 个答案:

答案 0 :(得分:-1)

通过将父容器div设置为width:100%并将svg width属性设置为100%,可以轻松完成此操作。 (viewbox属性确保保留纵横比)

var flowers = [{
    "name": "Hydrangia",
    "latin": "Hydrangea",
    "light": "Sun",
    "ease": 3
  },
  {
    "name": "Chrysanthemum",
    "latin": "Chrysanthemum",
    "light": "Part Sun",
    "ease": 1
  },
  {
    "name": "Peony",
    "latin": "Paeonia",
    "light": "Part Sun",
    "ease": -1
  },
  {
    "name": "Orchid",
    "latin": "Paeonia",
    "light": "Shade",
    "ease": -5
  },
  {
    "name": "Fern",
    "latin": "Dryopteris",
    "light": "Shade",
    "ease": 5
  },
  {
    "name": "Rose",
    "latin": "Rosa",
    "light": "Sun",
    "ease": -4
  },
  {
    "name": "Tulip",
    "latin": "Tulipa",
    "light": "Sun",
    "ease": -2
  },
  {
    "name": "Daisy",
    "latin": "Bellis perennis",
    "light": "Part Sun",
    "ease": 4
  }
];

flowers.map(function(flower) {
  flower["value"] = Math.floor(Math.random() * 100) + 1;
  return flower;
});

var width = window.innerWidth,
  height = window.innerHeight,
  bar_width = width / flowers.length;

var flower_domain = d3.extent(flowers, function(d) {
  return d.value;
});

//test our range
//console.log(flower_domain);

var bar_height = d3.scale.linear()
  .domain(flower_domain)
  .range([0, height]);

var svg = d3.select("#content").append("svg")
  .attr("viewBox", "0 0 " + width + " " + height)
  .attr("width", '100%')
  .attr("height", height);

var rects = svg.selectAll("rect")
  .data(flowers)
  .enter()
  .append("rect");

rects
  .attr("x", function(d, i) {
    return i * bar_width;
  })
  .attr("y", function(d) {
    return height - bar_height(d["value"]);
  })
  .attr("width", bar_width)
  .attr("height", function(d) {
    return bar_height(d["value"]);
  });
body {
  font-size: 16px;
  line-height: 1.5em;
  color: #333333;
  font-family: 'Helvetica Neue', Helvetica, sans-serif;
}

div#content {
  margin: auto;
  width: 100%;
}

div#content>h1 {
  margin: 20px;
  text-align: center;
}

div#content>div.flower>* {
  margin: 0;
}

div#content>div.flower {
  display: inline-block;
  padding: 15px 20px;
  margin: 10px;
  vertical-align: top;
}

div#content div.flower>img {
  width: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div id="content">
  <h1>My Favorite Flowers</h1>
</div>