Reputation: 6277
I'm wanting to scale this bar chart to the size of it's container. Ideally do something like w = '100%', h = '100%'. Any way I may do this?
<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) + ")";
});
Upvotes: 3
Views: 2057
Reputation: 884
You can ask for the width of your container (or any given element) with the style function, like this:
var width = parseInt(d3.select(".test").style("width"),10);
var height = parseInt(d3.select(".test").style("height"),10);
The last parameter (10) indicates that you want to use the decimal system (if I am not mistaken).
So you can set the width of your svg element to that width. I would even suggest you make a function out of it and call that function on a resize event, so your svg looks like a fluid/responsive element.
you can do that as following:
d3.select(window).on('resize', function(){/* your svg and chart code */});
EDIT: On rereading your question, it appears to me that I might have misunderstood your question. D3 has scaling functions to scale your data so it fits into your svg container. If your div element is not responsive, then you should just set your svg width and height the same as your div element, and use scales on your data so your chart fits in the svg container. More info on scales you can find here: quantitative scales
Upvotes: 4
Reputation: 303
try to change the height and width of your div to its column height and width like this http://jsfiddle.net/elviz/mo363jm7/2/
<div class="test" style="height:100px;width:200px;overflow:hidden"></div>
Upvotes: 0