Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
973 views
in Technique[技术] by (71.8m points)

Transitioning bar chart with combobox variable toggle in d3.js

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...