Skip to content

Instantly share code, notes, and snippets.

@darthmall
Last active August 10, 2016 01:09
Show Gist options
  • Save darthmall/7ad8b77249f67d15ebe17b1ec803a235 to your computer and use it in GitHub Desktop.
Save darthmall/7ad8b77249f67d15ebe17b1ec803a235 to your computer and use it in GitHub Desktop.
Animated bar chart transitions
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.axis .domain {
display: none;
}
.tick line {
stroke: #CCC;
}
rect {
fill: #65a4e0;
}
</style>
<svg width="960" height="500">
<g class="margin">
<g class="x axis"></g>
<g class="content"></g>
</g>
</svg>
<script src="//d3js.org/d3.v4.min.js"></script>
<script>
var margin = {
top: 0,
right: 8,
bottom: 24,
left: 8
};
var bandwidth = 10;
var gutter = 2;
// Just some random numbers for the charts
var data = [
[22, 19, 7, 6, 4],
[29, 20, 19, 19, 12, 8, 2, 1]
];
var index = 0;
var svg = d3.select("svg"),
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom;
svg.select(".margin").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var x = d3.scaleLinear().range([0, width]);
var xAxis = d3.axisBottom(x);
var g = svg.select(".content"),
gX = svg.select(".x.axis");
function update(group) {
x.domain([0, d3.max(data[group])]);
var t = d3.transition()
.duration(750)
.ease(d3.easeCubicOut);
var bar = g.selectAll("rect")
.data(data[group], function (d, i) { return d + "-" + i; });
bar.exit()
.transition(t).delay(function (d, i) { return i * 20; })
.attr("x", function () { return +d3.select(this).attr("width"); })
.attr("width", 0)
.remove();
bar.enter().append("rect")
.attr("y", function (d, i) { return i * (bandwidth + gutter); })
.attr("height", bandwidth)
.merge(bar).transition(t).delay(function (d, i) { return 175 + i * 20; })
.attr("width", function (d) { return x(d); });
gX.transition(t)
.call(xAxis.tickSize(data[group].length * (bandwidth + gutter) - gutter));
}
window.setTimeout(function tick() {
update(index);
index = (index + 1) % 2;
window.setTimeout(tick, 2000);
}, 0);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment