缩放D3条形图到容器大小

Scaling D3 bar chart to container size

本文关键字:D3 条形图 缩放      更新时间:2023-09-26

我想把这个条形图缩放到它的容器大小。理想的做法是w = '100%', h = '100%'。我能帮上忙吗?

http://jsfiddle.net/mo363jm7/

<div class="test" style="height:50px;width:100px;overflow:hidden"></div>
//Width and height
var w = 200,
    h = 100,
    barPadding = 1,
    dataset = [ 5, 10, 13, 19, 21, 25, 22, 18, 15, 13,
               11, 12, 15, 20, 18, 17, 16, 18, 23, 25 ];
//Create SVG element
var svg = d3.select(".test")
            .append("svg")
            .attr("width", w)
            .attr("height", h);
svg.selectAll("rect")
    .data(dataset)
    .enter()
    .append("rect")
    .attr("x", function(d, i) {
        return i * (w / dataset.length);
    })
    .attr("y", function(d) {
        return h - (d * 4);
    })
    .attr("width", w / dataset.length - barPadding)
    .attr("height", function(d) {
        return d * 4;
    })
    .attr("fill", function(d) {
        return "rgb(0, 0, " + (d * 10) + ")";
    });

您可以使用style函数请求容器(或任何给定元素)的宽度,如下所示:

   var width = parseInt(d3.select(".test").style("width"),10);
   var height =  parseInt(d3.select(".test").style("height"),10);

最后一个参数(10)表示您想使用十进制(如果我没弄错的话)。

因此,您可以将svg元素的宽度设置为该宽度。我甚至建议您用它创建一个函数,并在调整大小事件时调用该函数,这样您的svg看起来就像一个流体/响应式元素。

你可以这样做:

d3.select(window).on('resize', function(){/* your svg and chart code */});
编辑:重读你的问题,我觉得我可能误解了你的问题。D3具有缩放功能,可以缩放数据,使其适合svg容器。如果div元素没有响应,那么您应该将svg的宽度和高度设置为与div元素相同,并在数据上使用缩放,以便图表适合svg容器。你可以在这里找到更多关于尺度的信息:定量尺度

尝试将div的高度和宽度更改为其列的高度和宽度,如下http://jsfiddle.net/elviz/mo363jm7/2/

  <div class="test" style="height:100px;width:200px;overflow:hidden"></div>