Quick example demonstrating how to sort a bar chart and animate the reordering. The staggered delay makes it easier to follow individual bars, per Heer & Robertson. Built with d3.js.
-
-
Save recursionbane/8377c3386e9dd19cc652d9b577a0c6e0 to your computer and use it in GitHub Desktop.
Sortable Bar Chart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
license: gpl-3.0 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<meta charset="utf-8"> | |
<body> | |
<style> | |
body { | |
font: 10px sans-serif; | |
} | |
.bar rect { | |
fill: steelblue; | |
} | |
.bar text { | |
fill: white; | |
} | |
.axis path, .axis line { | |
fill: none; | |
stroke: black; | |
shape-rendering: crispEdges; | |
} | |
</style> | |
<script src="//d3js.org/d3.v3.min.js"></script> | |
<script> | |
var margin = {top: 0, right: 10, bottom: 20, left: 10}, | |
width = 960 - margin.left - margin.right, | |
height = 500 - margin.top - margin.bottom; | |
var index = d3.range(24), | |
data = index.map(d3.random.normal(100, 10)); | |
var x = d3.scale.linear() | |
.domain([0, d3.max(data)]) | |
.range([0, width]); | |
var y = d3.scale.ordinal() | |
.domain(index) | |
.rangeRoundBands([0, height], .1); | |
var svg = d3.select("body").append("svg") | |
.attr("width", width + margin.left + margin.right) | |
.attr("height", height + margin.top + margin.bottom) | |
.append("g") | |
.attr("transform", "translate(" + margin.left + "," + margin.top + ")"); | |
var bar = svg.selectAll(".bar") | |
.data(data) | |
.enter().append("g") | |
.attr("class", "bar") | |
.attr("transform", function(d, i) { return "translate(0," + y(i) + ")"; }); | |
bar.append("rect") | |
.attr("height", y.rangeBand()) | |
.attr("width", x); | |
bar.append("text") | |
.attr("text-anchor", "end") | |
.attr("x", function(d) { return x(d) - 6; }) | |
.attr("y", y.rangeBand() / 2) | |
.attr("dy", ".35em") | |
.text(function(d, i) { return i; }); | |
svg.append("g") | |
.attr("class", "x axis") | |
.attr("transform", "translate(0," + height + ")") | |
.call(d3.svg.axis() | |
.scale(x) | |
.orient("bottom")); | |
var sort = false; | |
setInterval(function() { | |
if (sort = !sort) { | |
index.sort(function(a, b) { return data[a] - data[b]; }); | |
} else { | |
index = d3.range(24); | |
} | |
y.domain(index); | |
bar.transition() | |
.duration(750) | |
.delay(function(d, i) { return i * 50; }) | |
.attr("transform", function(d, i) { return "translate(0," + y(i) + ")"; }); | |
}, 5000); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment