问题
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