Transitioning bar chart with combobox variable toggle in d3.js

烈酒焚心 提交于 2019-12-25 01:44:37

问题


I've developed a simple d3.js line graph that allows the user to toggle between variables in a json:

http://plnkr.co/edit/8r0DBxVFgY6SJKbukWh5?p=preview

However, I need this to be a bar graph instead of a line graph and I can't figure out how to transition bars, or anything else that uses a selectAll to draw, for that matter, such as points. In this case, I've been drawing the bars in the d3.json function like so:

svg.selectAll(".bar")
  .data(data)
  .enter().append("rect")
  .attr("class", "bar")
  .attr("x", function(d) { return x(d.watershed); })
  .attr("width", x.rangeBand())
  .attr("y", function(d) { return y(d.variable); })
  .attr("height", function(d) { return height - y(d.variable); });

The problem is: what do I put in the updateData function to transition the bars to reflect the new data? I feel like I need to set up a variable to call the svg.selectAll('.bar") from both the d3.json and updateData functions (as with var valueLine), but I couldn't find examples of how that would look in this context.


回答1:


I've modified your code here to do what you want. Apart from the code you mention in the JSON handler, you need the following in the update function:

svg.selectAll(".bar")
   .data(data)
   .transition().duration(750)
   .attr("x", function(d) { return x(d.watershed); })
   .attr("y", function(d) { return y(d.variable); })
   .attr("height", function(d) { return height - y(d.variable); });

This updates the bars with a transition.

I've also modified the value for the interval between bars that you gave to the scale -- it was so large that the bars themselves had 0 width.



来源:https://stackoverflow.com/questions/16484396/transitioning-bar-chart-with-combobox-variable-toggle-in-d3-js

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!