8 Transitions
Read IDVW2, Chapter 9: transitions section (pp. 158-178)
8.1 Examples
Open Developer Tools and try in the Console:
.select("svg")
d3.selectAll("circle")
.transition()
.duration(2000)
.attr("cx", "275");
.select("svg")
d3.selectAll("circle")
.transition()
.duration(2000)
.attr("cx", "25")
.attr("fill", "green");
8.2 Do this
Run simultaneous transitions on different selections:
.select("svg").selectAll("circle#henry").transition()
d3.duration(2000).attr("cx", "275");
.select("svg").selectAll("circle.apple").transition()
d3.duration(2000).attr("cx", "25");
Run sequential transitions on the same selection in one chain:
.select("svg").selectAll("circle")
d3.transition().duration(2000).attr("cx", "275")
.transition().duration(2000).attr("cx", "25");
Transition from something to something:
.select("svg").append("circle")
d3.attr("cx", "200")
.attr("cy", "100")
.attr("r", "5")
.attr("fill", "lightblue")
.transition()
.duration(4000)
.attr("r", "25")
.attr("fill", "blue");
8.3 Not this
DO NOT run two transitions on the same selection at the same time (see p. 172).
(What works in the Console will not work in a script.)
.select("svg").selectAll("circle").transition()
d3.duration(2000).attr("cx", "250");
.select("svg").selectAll("circle").transition()
d3.duration(2000).attr("cx", "75");
DO NOT transition from nothing to something:
.select("svg").append("circle")
d3.transition()
.duration(2000)
.attr("cx", "200")
.attr("cy", "100")
.attr("r", "25")
.attr("fill", "red");
DO NOT store a selection with a transition (it’s no longer a selection with the transition):
Try this:
const circ = d3.select("svg")
.selectAll("circle")
.data([50, 95, 100, 200, 50, 150, 250])
.enter()
.append("circle")
.attr("cx", d => d)
.attr("cy", "100")
.attr("fill", "blue")
.attr("r", "0")
.transition()
.duration(2000)
.attr("r", "25");
And then this:
.attr("fill", "green"); circ
DO NOT put a transition before a merge:
.select("svg")
d3.selectAll("circle")
.transition()
.duration(2000)
.attr("cx", "300")
.merge("oldcirc")
.attr("fill", "green");
BE AWARE that not everything transitions (for example, text doesn’t.)
8.4 Strategy
Example 1
Think carefully about what you want to happen, and then decide what goes before and after the transition.
Plan what you want to happen:
new bars appear on the right side with orange fill
new bars slide into place from the right as old bars are repositioned
new bars transition to blue
removed bars transition to right before disappearing
8.5 Exercise : Bar chart with transitions
Download and make changes to bar_transition.html in a text editor so the transitions work as shown below.
Solution
Further reading: Working with Transitions.