Skip to content

Instantly share code, notes, and snippets.

@SpaceActuary
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SpaceActuary/29c2c89bcdf66c2553c2 to your computer and use it in GitHub Desktop.
Save SpaceActuary/29c2c89bcdf66c2553c2 to your computer and use it in GitHub Desktop.
Bar Chart Transitions - Positive to Negative
<!DOCTYPE html>
<meta charset="utf-8">
<style>
</style>
<body>
<button onClick="flip1();">Flip - Single Transition, Cubic-In-Out</button>
<button onClick="flip2();">Flip - Double Transition, Cubic-Out, Cubic-In</button>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var data = [5, 3, 7, 2, 9, 6, 12, 8, 10, 11],
w = 900, // width
h = 600, // height
m = 20, // margin
t = 1000, // transition time
b = w / data.length // block width
var svg = d3.select("body").append("svg")
.attr("width", w + 2 * m)
.attr("height", h + 2 * m)
.append("g")
.attr("transform", "translate(" + m + "," + m + ")");
svg.append("line")
.style("stroke", "black")
.attr("x1", 0)
.attr("x2", w)
.attr("y1", h / 2)
.attr("y2", h / 2)
var redraw = function(data, easeType){
var bars = svg.selectAll("rect")
.data(data)
bars.enter().append("rect")
.attr("fill", "steelblue")
.attr("x", function(d, i){ return i * b + 5; })
.attr("width", b - 10)
.attr("y", h / 2)
.attr("height", 0);
if(easeType == "double"){
// make two transitions:
// 1. transition the bar heights to zero using half of the transition time
// 2. transition the bar heigths to their new height using the remaining time
bars.transition().duration(t / 2).ease("cubic-in")
.attr("y", h / 2)
.attr("height", 0)
.transition().duration(t / 2).ease("cubic-out")
.attr("y", function(d){ return Math.min(h / 2, h / 2 - 10 * d); })
.attr("height", function(d){ return Math.abs(10 * d); });
} else {
// the "default" transition--just update the attributes at once
// this gives a funny result--the bars never get to zero,
// but rather "float" over the axis.
bars.transition().duration(t)
.attr("y", function(d){ return Math.min(h / 2, h / 2 - 10 * d); })
.attr("height", function(d){ return Math.abs(10 * d); });
}
}
redraw(data);
var flip1 = function(){
data = data.map(function(d){ return -d; });
redraw(data, "single");
}
var flip2 = function(){
data = data.map(function(d){ return -d; });
redraw(data, "double");
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment