Reputation: 69
How can I reverse how my vertical bar is drawn? I want it to be drawn from the bottom to the top. It is important to maintain the right representation of the dataset
https://jsfiddle.net/adai183/ztsh1ptx/
var dataset = [ 10, 80, 5, 5];
//Create SVG element
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("fill", "rgb(250, 128, 114)")
.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", 0)
.transition().duration(750).ease("linear")
.attr("height", function(d) {
return d * 4;
});
Upvotes: 2
Views: 698
Reputation: 32327
Do it like this:
.attr("y", function(d) {
return h; //set y to max height
})
.attr("width", w / dataset.length - barPadding)
.attr("height", 0)//height of the bars initially is 0
.transition().duration(750).ease("linear")//on transition
.attr("y", function(d) {
return d*4;//set the y to its value
})
.attr("height", function(d) {
return h - (d * 4);//set the height to max height - y's value
})
working code here
EDIT
For solving that problem make a scale for y:
var y = d3.scale.linear()
.range([h, 0])
.domain([0,100]);//since values vary between 0 and 100
Now use this scale to give height to your bar chart.
.transition().duration(750).ease("linear")
.attr("y", function(d) {
return y(d);
})
.attr("height", function(d) {
return h - y(d);
})
working example here
Hope this helps!
Upvotes: 3