Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...