D3.js Transitions

前端 未结 2 882
醉梦人生
醉梦人生 2020-12-31 01:31

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

相关标签:
2条回答
  • 2020-12-31 02:04

    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!

    0 讨论(0)
  • 2020-12-31 02:09

    Remember the x-scale is backwards to what you would expect (bars have to be built upwards from the bottom (where bottom = svg height). Use Transition to animate bars on enter.

    An example of what I think you are trying to achieve can be found here: http://bl.ocks.org/jamesleesaunders/f32a8817f7724b17b7f1

    All the best,

    Jim

    0 讨论(0)
提交回复
热议问题