我想将此条形图缩放到其容器的大小。理想情况下做类似 w = '100%', h = '100%' 的事情。我可以这样做吗?
<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 容器。您可以在此处找到有关体重秤的更多信息:quantitative scales
关于javascript - 将 D3 条形图缩放到容器大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31446297/