I am trying to create an animated bar graph using d3.js. I want the bars to appear one by one like this example http://nvd3.com/ghpages/multiBar.html . I was able to create a similar behavior but the motion starts from the height of the bar builds the bar towards the x-axis, however I want the motion to start from the x-axis and go to the height of the bar like the example.
Much simplified version of my code: http://jsfiddle.net/gorkem/ECRMd/
Any help would be much appreciated
Because the origin of the coordinate system is from the top-left, the 'y' value is anchored at the top of each bar. If the 'y' value is fixed, and the 'height' is increased, it looks like the bars grow down. In order to make the bars grow from the bottom, you'll need to transition both the 'y' and the 'height' at the same time.
This should be what you're looking for, I've only changed two lines.
chart.selectAll("rect")
.data(data)
.enter().append("rect")
.attr("x", function(d, i) { return x(i) - .5; })
.attr("y", function(d) { return h - .5; }) //new----
.attr("width", w)
.transition().delay(function (d,i){ return i * 300;})
.duration(300)
.attr("height", function(d) { return y(d.value); })
.attr("y", function(d) { return h - y(d.value) - .5; }); //new-----
I've started the 'y' value at the bottom of the chart (h - 0.5). Then when you transition, you increase the 'height' (y(d.value)) and decrease the 'y' (h - y(d.value)) at the same rate. This has the effect of fixing the bottom of the bar to the axis.
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With